configure button on canvas in python - python

I'm working on GUI project and I'm trying to configure a button color and text but it gives me an error..
here is a sample of my code:
from tkinter import*
from tkinter import ttk
#root
root = Tk()
root.geometry('640x520')
#Canvas
myCanvas = Canvas(root, width=350, height=300, bd=0, highlightthickness=0)
myCanvas.pack(fill='both', expand=True)
def qu1():
global myCanvas
myCanvas.itemconfig(Q1,bg='green',text= 'Done')
Q1 = Button(root, width=15, height=10, bg='#F3C4B7',fg='white', text='1', command=qu1)
myCanvas.create_window(10,10, anchor='nw', window=Q1)
root.mainloop()
it gives me this error:
line 12, in qu1
myCanvas.itemconfig(Q1,bg='green',text= 'Done')
_tkinter.TclError: invalid boolean operator in tag search expression

Already stated:
itemconfig applies to Canvas objects
You can do:
from tkinter import*
root = Tk()
root.geometry('640x520')
myCanvas = Canvas(root, width=350, height=300, bd=0, highlightthickness=0)
myCanvas.pack(fill='both', expand=True)
buttonBG = myCanvas.create_rectangle(0, 0, 100, 30, fill="grey40", outline="grey60")
buttonTXT = myCanvas.create_text(50, 15, text="click")
def qu1(event):
myCanvas.itemconfig(buttonBG, fill='red')
myCanvas.itemconfig(buttonTXT, fill='white')
myCanvas.tag_bind(buttonBG, "<Button-1>", qu1)
myCanvas.tag_bind(buttonTXT, "<Button-1>", qu1)
root.mainloop()
Or change the button itself:
from tkinter import*
root = Tk()
root.geometry('640x520')
myCanvas = Canvas(root, width=350, height=300, bd=0, highlightthickness=0)
myCanvas.pack(fill='both', expand=True)
def qu1():
Q1.configure(bg="#234")
Q1 = Button(root, width=15, height=10, bg='#F3C4B7',fg='white', text='1', command=qu1)
myCanvas.create_window(10,10, anchor='nw', window=Q1)
root.mainloop()

Related

why is .grid giving me an error when I am trying to move my button

import time
import tkinter as tk
from tkinter import scrolledtext
win = tk.Tk()
win.title("My First Game")
win.configure(bg="black")
win.geometry("640x400")
label = tk.Label(win, text="test", fg="red", bg="black").pack()
canvas1 = tk.Canvas(win, width=130, height=20)
canvas1.pack()
entry1 = tk.Entry(win, font="Helvetica 10")
canvas1.create_window(65, 10, window=entry1)
entry1.insert(0, "Type here")
def shortcut():
Shortcut = tk.Label(win, fg="red", bg="black", text="test2")
Shortcut.pack()
button1 = tk.Button(win, text="Enter", fg="red", bg="black", command=shortcut)
button1.pack()
exit_button = tk.Button(win, text="Quit", padx=4, pady=2, bg="black", fg="red", command=quit)
exit_button.pack()
exit_button.grid(row=0, column=2)
win.mainloop()
Why is this giving me an error? I tried in a separate project with just a black screen and the button and it worked fine. But when I put it in the code above it doesn't work
line 42, in <module> exit_button.grid(row=0, column=2)
_tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack
As #10Rep mentioned in comment - you can remove grid() to resolve problem with error.
import tkinter as tk
# --- functions ---
def shortcut():
shortcut = tk.Label(win, text="test2")
shortcut.pack()
# --- main ---
win = tk.Tk()
label = tk.Label(win, text="test")
label.pack()
canvas1 = tk.Canvas(win) #, width=130, height=20)
canvas1.pack()
entry1 = tk.Entry(canvas1)
canvas1.create_window(0, 0, window=entry1, anchor='nw')
entry1.insert(0, "Type here")
button1 = tk.Button(win, text="Enter", command=shortcut)
button1.pack()
exit_button = tk.Button(win, text="Quit", command=win.destroy)
exit_button.pack()
win.mainloop()
But I expect that you used grid() to organize two buttons in one line.
Problem is that you can't mix pack() and grid() in one window/frame and I see two solutions:
First is to use only grid() to organize all widgets
import tkinter as tk
# --- functions ---
def shortcut():
shortcut = tk.Label(win, text="test2")
shortcut.grid(row=3, column=0, columnspan=2)
# --- main ---
win = tk.Tk()
label = tk.Label(win, text="test")
label.grid(row=0, column=0, columnspan=2)
canvas1 = tk.Canvas(win) #, width=130, height=20)
canvas1.grid(row=1, column=0, columnspan=2)
entry1 = tk.Entry(canvas1)
canvas1.create_window(0, 0, window=entry1, anchor='nw')
entry1.insert(0, "Type here")
button1 = tk.Button(win, text="Enter", command=shortcut)
button1.grid(row=2, column=0)
exit_button = tk.Button(win, text="Quit", command=win.destroy)
exit_button.grid(row=2, column=1)
win.mainloop()
Second is to put Frame (using pack()) and put buttons inside this frame using grid()
import tkinter as tk
# --- functions ---
def shortcut():
shortcut = tk.Label(win, text="test2")
shortcut.pack()
# --- main ---
win = tk.Tk()
label = tk.Label(win, text="test")
label.pack()
canvas1 = tk.Canvas(win) #, width=130, height=20)
canvas1.pack()
entry1 = tk.Entry(canvas1)
canvas1.create_window(0, 0, window=entry1, anchor='nw')
entry1.insert(0, "Type here")
# - frame with grid -
f = tk.Frame(win)
f.pack()
button1 = tk.Button(f, text="Enter", command=shortcut)
button1.grid(row=0, column=0)
exit_button = tk.Button(f, text="Quit", command=win.destroy)
exit_button.grid(row=0, column=1)
# -
win.mainloop()
or using pack(side=...)
import tkinter as tk
# --- functions ---
def shortcut():
shortcut = tk.Label(win, text="test2")
shortcut.pack()
# --- main ---
win = tk.Tk()
label = tk.Label(win, text="test")
label.pack()
canvas1 = tk.Canvas(win) #, width=130, height=20)
canvas1.pack()
entry1 = tk.Entry(canvas1)
canvas1.create_window(0, 0, window=entry1, anchor='nw')
entry1.insert(0, "Type here")
# - frame with pack(side=...) -
f = tk.Frame(win)
f.pack()
button1 = tk.Button(f, text="Enter", command=shortcut)
button1.pack(side='left')
exit_button = tk.Button(f, text="Quit", command=win.destroy)
exit_button.pack(side='left')
# -
win.mainloop()

Image not showing (tkinter in python)

When I try to insert the image into my Tkinter window all that shows up is
this
import tkinter as tk
root = tk.Tk()
root.title("To Do List")
canvas = tk.Canvas(root, height=900, width=1000, bg='white')
frame = tk.Frame(root, bg="#000000")
img = tk.PhotoImage("deathnote.png")
entry = tk.Entry(frame, font='system', fg='white', bg='black')
imglabel = tk.Label(frame, image=img)
canvas.grid(row=0, column=0)
frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1)
imglabel.grid(row=0, column=2)
entry.grid(row=1, column=1)
root.mainloop()
Try using PIL:
import tkinter as tk
from PIL import ImageTk, Image
root = tk.Tk()
root.title("To Do List")
canvas = tk.Canvas(root, height=900, width=1000, bg='white')
frame = tk.Frame(root, bg="#000000")
img = ImageTk.PhotoImage(Image.open("deathnote.png"))
entry = tk.Entry(frame, font='system', fg='white', bg='black')
imglabel = tk.Label(frame, image=img)
canvas.grid(row=0, column=0)
frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1)
imglabel.grid(row=0, column=2)
entry.grid(row=1, column=1)
root.mainloop()

Tkinter update label text

I am trying to update the label text in "label_enter_what" in accordance to what they chose in "drop". So if they choose "Energy", the label would change to: Enter wavelength in chosen unit below", for example. Sorry if the code looks messy, it's my first time coding. This is supposed to be a photon property calculator that i am making for fun because in physics we are currently doing this, but with pens and calculators.
import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
HEIGHT = 600
WIDTH = 900
root = tk.Tk()
root.title("Photon property calculator")
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
background_image = ImageTk.PhotoImage(Image.open('interference.jpg'))
background_label = tk.Label(root, image=background_image)
background_label.place(relheight=1, relwidth=1)
frame = tk.Frame(root, bg='#3E3E3E', bd=5)
frame.place(relx=0.5, rely=0.1, relheight=0.1, relwidth=0.75, anchor='n')
frame_upper = tk.Frame(root, bg='#3E3E3E', bd=5)
frame_upper.place(relx=0.5, rely=0.03, relheight=0.06, relwidth=0.75, anchor='n')
label_what_to_calc = tk.Label(frame_upper, bg='white', text='Enter what \n to calculate')
label_what_to_calc.place(relx=0, rely=0, relheight=1, relwidth=0.15)
label_enter_what = tk.Label(frame_upper, bg='white', text='Enter * in a chosen unit below.')
label_enter_what.place(relx=0.2, relheight=1, relwidth=0.2)
label_unit = tk.Label(frame_upper, bg='white', text='')
label_unit.place(relx=0.5, relheight=1, relwidth=0.1)
lower_frame = tk.Frame(root, bg='#60A8FF', bd=10)
lower_frame.place(relx=0.5, rely=0.3, relheight=0.5, relwidth=0.75, anchor='n')
entry_value = tk.Entry(frame, font=40, bg='white')
entry_value.place(relx=0.175, rely=0, relheight=1, relwidth=0.4)
OPTIONS = [
"Energy",
"Frequency",
"Wavelength"
]
clicked = StringVar()
clicked.set(OPTIONS[0])
drop = tk.OptionMenu(frame, clicked, *OPTIONS)
drop.place(relx=0, rely=0, relheight=1, relwidth=0.15)
OPTIONS_UNITS = ["μm",
"nm",
"pm",
"aJ",
"zJ",
]
clicked_1 = StringVar()
clicked_1.set(OPTIONS_UNITS[1])
drop_units = tk.OptionMenu(frame, clicked_1, *OPTIONS_UNITS)
drop_units.place(relx=0.6, rely=0, relheight=1, relwidth=0.09)
button = tk.Button(frame, text='Calculate!', font=40, bg="#F96612", fg='black')
button.place(relx=0.7, relheight=1, relwidth=0.3)
label = tk.Label(lower_frame, bg='white', text=clicked.get())
label.place(relheight=1, relwidth=1)
root.mainloop()
You can use
tk.OptionMenu( ... command=function)
to run function which will get selected value and it will change text in label
import tkinter as tk
# --- functions ---
def on_select(value):
label['text'] = value
# --- main ---
root = tk.Tk()
label = tk.Label(root, text='?')
label.pack()
OPTIONS = ["Energy", "Frequency", "Wavelength"]
value_var = tk.StringVar(value=OPTIONS[0])
op = tk.OptionMenu(root, value_var, *OPTIONS, command=on_select)
op.pack()
root.mainloop()

Alarm clock not working on my tkinter GUI

Im trying to make a tkinter GUI with an alarm clock and weather. My alarm clock is not working for some reason. I "borrowed" the code from another person and it works on his/her program for some reason but not mine.
I haven't tried anything because im very new to python and coding in general.
import tkinter as tk
from tkinter import *
from tkinter.ttk import *
import os
import time
from time import strftime
from datetime import date
today = date.today()
HEIGHT = 500
WIDTH = 500
def test_function(entry):
label3 = tk.Label(lower_frame, bg='white',font=('Courier',15), text=entry, anchor='nw', justify='left', bd=4)
label3.place(relwidth=1, relheight=1)
root = tk.Tk()
def quit_function():
root.destroy()
def SubmitButton():
AlarmTime= alarm_entry.get()
CurrentTime= time.strftime("%H:%M")
while AlarmTime != CurrentTime:
CurrentTime = time.strftime("%H:%M")
time.sleep(1)
if AlarmTime == CurrentTime:
label3 = tk.Label(lower_frame, bg='white',font=('Courier',15), text="Perkele", anchor='nw', justify='left', bd=4)
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
background_image = tk.PhotoImage(file='landscape.png')
bg_label = tk.Label(root, image=background_image)
bg_label.place(x=0, y=0, relwidth=1, relheight=1)
frame = tk.Frame(root, bg='#08AEF6', bd=5)
frame.place(relx=0.5, rely=0.125, relwidth=0.75, relheight=0.1, anchor='n')
entry = tk.Entry(frame, font=40)
entry.place(relwidth=0.65, relheight=1)
button = tk.Button(frame, font=40, text="Get Weather", bg='gray', fg='black', command=lambda: test_function(entry.get()))
button.place(relx=0.7, relwidth=0.3, relheight=1)
lower_frame = tk.Frame(root, bg='#08AEF6', bd=10)
lower_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.6, anchor='n')
up_frame = tk.Frame(root, bg='#08AEF6', bd=5)
up_frame.place(relx=0.675, rely=0, relwidth=0.4, relheight=0.1, anchor='n')
alarm_button = tk.Button(up_frame, text="Set alarm time", bg='gray', fg='black', font=40, command=SubmitButton)
alarm_button.place(relx=0.7, rely=0.5, relwidth=0.3, relheight=0.45)
label3 = tk.Label(lower_frame, bg='white')
label3.place(relwidth=1, relheight=1)
label = tk.Label(up_frame, bg='white')
label.place(relx=0, relwidth=0.695, relheight=0.5)
date1 = tk.Label(up_frame, bg='white', text=today, font=40)
date1.place(relx=0, rely=0.5, relwidth=0.695, relheight=0.5)
quit_frame = tk.Frame(root, bg='#08AEF6', bd=5)
quit_frame.place(relx=0, rely=0, relwidth=0.1, relheight=0.1)
quit_button = tk.Button(quit_frame, command=quit_function, text="Quit")
quit_button.place(relwidth=1, relheight=1)
alarm_entry = tk.Entry(up_frame, font=40)
alarm_entry.insert(3, "esimerkiksi - 15:45")
alarm_entry.place(relx=0.7, rely=0, relwidth=0.3, relheight=0.45)
# label2 = tk.Label(lower_frame, bg='white')
root.overrideredirect(True)
root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
root.focus_set()
def time():
string = strftime('%H:%M:%S')
label.config(text = string, font='40')
label.after(1000, time)
time()
It gives me this error in line 33.
AttributeError: 'function' object has no attribute 'strftime'

How to insert a scrollbar and a form in a notebook widget with python and tkinter?

I am really new to python and currently I am trying to design a form using tkinter. I am stuck trying to insert an scrollbar and a form in a notebook since I haven't found an answer to my question, and it is simple "How can I insert a scrollbar and a form in a notebook tkinter widget?"... As you can see is simple for you, but not for a newbie like me!
However, this is what I have done so far, fortunately it does show the scrollbar, but it crashes when I try insert the form into the notebook!
Note: My python version is Python 2.7.3 with EPD_free 7.3-2 (32-bit)
import Tkinter
from Tkinter import *
from ttk import *
import tkMessageBox
import ttk
import Tkinter as tk
root = Tk()
root.title("Model_A")
root.resizable(0,0)
# start of Notebook (multiple tabs)
notebook = ttk.Notebook(root)
notebook.pack(fill=BOTH, expand=True)
notebook.pressed_index = None
#Child Frames
ContainerOne = Frame(notebook)
ContainerOne.pack(fill=BOTH, expand=True)
ContainerTwo = Frame(notebook)
ContainerTwo.pack(fill=BOTH, expand=True)
ContainerThree = Frame(notebook)
ContainerThree.pack(fill=BOTH, expand=True)
ContainerFour = Tkinter.Frame(notebook)
ContainerFour.pack(fill=BOTH, expand=True)
#Create the pages
notebook.add(ContainerOne, text='Mode A')
notebook.add(ContainerTwo, text='Mode B')
notebook.add(ContainerThree, text='Mode C')
notebook.add(ContainerFour, text='Mode D')
canvas = Canvas(ContainerOne, width=200, height=400)
scroll = Scrollbar(ContainerOne, command=canvas.yview)
canvas.config(yscrollcommand=scroll.set, scrollregion=(0,0,100,1000))
canvas.pack(side=LEFT, fill=BOTH, expand=True)
scroll.pack(side=RIGHT, fill=Y)
canvas = Canvas(ContainerTwo, width=200, height=400)
scroll = Scrollbar(ContainerTwo, command=canvas.yview)
canvas.config(yscrollcommand=scroll.set, scrollregion=(0,0,100,1000))
canvas.pack(side=LEFT, fill=BOTH, expand=True)
scroll.pack(side=RIGHT, fill=Y)
canvas = Canvas(ContainerThree, width=200, height=400)
scroll = Scrollbar(ContainerThree, command=canvas.yview)
canvas.config(yscrollcommand=scroll.set, scrollregion=(0,0,100,1000))
canvas.pack(side=LEFT, fill=BOTH, expand=True)
scroll.pack(side=RIGHT, fill=Y)
canvas = Canvas(ContainerFour, width=200, height=400)
scroll = Scrollbar(ContainerFour, command=canvas.yview)
canvas.config(yscrollcommand=scroll.set, scrollregion=(0,0,100,1000))
canvas.pack(side=LEFT, fill=BOTH, expand=True)
scroll.pack(side=RIGHT, fill=Y)
frame = Frame(canvas, width=200, height=1000)
canvas.create_window(100, 500, window=frame)
frameOne = None
def defocus(event):
event.widget.master.focus_set()
if __name__ == '__main__':
ContainerOne= Tkinter.Label(notebook, text=" 1. Enter Main Details: ", font=("fixedsys", "16","bold italic"))
frameOne.grid(row=2, columnspan=7, sticky='W', \
padx=5, pady=5, ipadx=5, ipady=5)
#Component Selection
componentComb= ttk.Combobox(ContainerOne, width="19")
componentComb = Combobox(ContainerOne, state="readonly", values=("A", "B", "C"))
componentComb.grid(column=4, row=4, columnspan="5", sticky="nswe")
componentComb.set("Main Selection")
root.mainloop()
If you take a look at the options of the Notebook widget, you can see that neither yview nor yscrollcommand are present. Besides, Frame widgets aren't scrollable either.
What you can do is to create a Canvas widget with a Scrollbar inside your frameOne, and then add a Frame to the canvas with create_window.
root = Tk()
root.resizable(0,0)
notebook = ttk.Notebook(root)
notebook.pack(fill=BOTH, expand=True)
notebook.pressed_index = None
container = Frame(notebook)
container.pack(fill=BOTH, expand=True)
notebook.add(container, text='Mode A')
canvas = Canvas(container, width=200, height=400)
scroll = Scrollbar(container, command=canvas.yview)
canvas.config(yscrollcommand=scroll.set, scrollregion=(0,0,100,1000))
canvas.pack(side=LEFT, fill=BOTH, expand=True)
scroll.pack(side=RIGHT, fill=Y)
frame = Frame(canvas, bg='white', width=200, height=1000)
canvas.create_window(100, 500, window=frame)
root.mainloop()
I have solved the problem I had with python and tkinter inserting form into a notebook as well as a scrollbar. I want to thank #A.Rodas for his kind help.
This is my code, hope you find it useful!
import Tkinter
from Tkinter import *
from ttk import *
import tkMessageBox
import math
import ttk
import Tkinter as tk
def defocus(event):
event.widget.master.focus_set()
# start of GUI code
root = Tk()
root.title("Model A")
root.resizable(0,0)
# start of Notebook (multiple tabs)
notebook = ttk.Notebook(root)
notebook.pack(fill=BOTH, expand=True)
notebook.pressed_index = None
# Child frames
ContainerOne = Frame(notebook)
ContainerOne.pack(fill=BOTH, expand=True)
ContainerTwo = Frame(notebook)
ContainerTwo.pack(fill=BOTH, expand=True)
# Create the pages
notebook.add(ContainerOne, text='Mode A')
notebook.add(ContainerTwo, text='Mode B')
canvas1 = Canvas(ContainerOne, width=1200, height=450)
scroll = Scrollbar(ContainerOne, command=canvas1.yview)
canvas1.config(yscrollcommand=scroll.set, scrollregion=(0,0,100,1000))
canvas1.pack(side=LEFT, fill=BOTH, expand=True)
scroll.pack(side=RIGHT, fill=Y)
canvas2 = Canvas(ContainerTwo, width=1200, height=450)
scroll = Scrollbar(ContainerTwo, command=canvas2.yview)
canvas2.config(yscrollcommand=scroll.set, scrollregion=(0,0,100,1000))
canvas2.pack(side=LEFT, fill=BOTH, expand=True)
scroll.pack(side=RIGHT, fill=Y)
frameOne = Frame(canvas1, width=800, height=450)
canvas1.create_window(250, 125, window=frameOne)
frameTwo = Frame(canvas2, width=800, height=450)
canvas2.create_window(200, 140, window=frameTwo)
# Main Frame
#Close Application Button
def quit(root):
root.destroy()
ttk.Button(root, text="Close Application", command=lambda root=root:quit(root)).pack()
if __name__ == '__main__':
#Main Part
stepOne = Tkinter.LabelFrame(frameOne, text=" 1. Enter Main Details: ", font=("fixedsys", "16","bold italic"))
stepOne.grid(row=0, columnspan=5, sticky='nsew', padx=5, pady=5, ipadx=5, ipady=5)
stepTwo = Tkinter.LabelFrame(frameOne, text=" 2. Calculate AP : ", font=("fixedsys", "16","bold italic"))
stepTwo.grid(row=2, columnspan=7, sticky='WE', padx=5, pady=5, ipadx=5, ipady=5)
# First Step Starts
# Component Selection
componentComb= ttk.Combobox(stepOne, width="19")
componentComb = Combobox(stepOne, state="readonly", values=("CDA", "VHS", "DVD"))
componentComb.grid(column=4, row=0, columnspan="5", sticky="nswe")
componentComb.set("Component Selection")
# Temperature Selection
tempComb = ttk.Combobox(stepOne, width="12")
tempComb = Combobox(stepOne, state="readonly", values=("-40", "-30", "-20","-10", "0",))
tempComb.grid(column=0, row=2, columnspan="2", sticky="w")
tempComb.set("Temperature Selection")
# Second Step Starts
inEncLbl = Tkinter.Label(stepTwo, text="Oxide:")
inEncLbl.grid(row=2, column=0, sticky='E', padx=5, pady=2)
inEncTxt = Tkinter.Entry(stepTwo, width=6)
inEncTxt.grid(row=2, column=1, sticky='w', pady=2)
outEncLbl = Tkinter.Label(stepTwo, text="Density Rate (DR):")
outEncLbl.grid(row=2, column=5, padx=5, pady=2)
outEncTxt = Tkinter.Entry(stepTwo, width=6)
outEncTxt.grid(row=2, column=7,sticky='w', pady=2)
#End Code
root.mainloop()

Categories