I am making an application that involves tkinter, and will eventually involve sockets. My code currently consists of this:
import tkinter as tk # imports tkinter module
from tkinter import * # imports tkinter module
a=tk.Tk()
a.title('Custodian Alert Tool')
List=['','','']
List.clear()
def Clear():
for widget in a.winfo_children(): # clears the window for the next Page
widget.destroy()
def Home():
Clear()
Label(a,text='Welcome to the Custodian Alert Tool.').pack()
Label(a,text='').pack()
SubmitButton=tk.Button(a,text='Submit A Ticket',command=Submit)
SubmitButton.pack()
ExitButton=tk.Button(a,text='Exit',command=Exit)
ExitButton.pack()
a.mainloop()
def Submit():
Clear()
def Append1(): # the button calls this function when pressed
List.append(x.get())
Gender()
Label(a,text='Which bathroom are you reporting for?').pack()
f=tk.Frame(a)
f.pack()
x=tk.StringVar()
E=tk.Entry(f,textvariable=x)
E.grid(row=1,column=1)
b1=tk.Button(f,text='Submit',command=Append1) # the error occurs after I click this button
b1.grid(row=1,column=2)
def Gender():
Clear()
def Append2(y):
List.append(y)
Issue()
Label(a,text='Boys or Girls?').pack()
f=tk.Frame(a)
f.pack()
b1=tk.Button(f,text='Boys',command=Append2('Boys'))
b1.grid(row=1,column=1)
b2=tk.Button(f,text='Girls',command=Append2('Girls'))
b2.grid(row=1,column=2)
def Issue():
Clear()
def Exit():
a.destroy()
Home()
When I click the b1 button under the Submit function, however, I get this:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1550, in __call__
return self.func(*args)
File "/Users/skor8427/Desktop/AlertClient.py", line 27, in Append1
Gender()
File "/Users/skor8427/Desktop/AlertClient.py", line 45, in Gender
b1=tk.Button(f,text='Boys',command=Append2('Boys'))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 2209, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 2139, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: bad window path name ".4610182280"
This is the biggest error I have ever gotten and I have no clue where to begin. Anyone know what I can do?
When you do this:
b1=tk.Button(f,text='Boys',command=Append2('Boys'))
It behaves exactly the same as this:
result = Append2('Boys'))
b1=tk.Button(f,text='Boys',command=result)
When Append2 is called, it calls Issue which calls Clear which destroys all of the children in a. f is in a so f gets destroyed. That means that you're trying to create b1 as a child of a widget that has been destroyed. And that is why you get the error "bad window path name" -- that cryptic string is the name of the widget that has been destroyed.
You need to modify the construction of b1 to be something like this:
b1 = Button(f, text='Boys', command=lambda: Append2('Boys'))`
That will defer the calling of Append2 until the button is clicked.
Related
I'm new to Graphic User Interface using Python. I was trying to open the Register page after clicking the "Register" button from the Login page. Then, return to the Login page when clicking "Return to Login". But it did not work.
login.py
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from register import Register
class Login:
def __init__(self):
self.loginw = Tk()
self.loginw.title("Login")
self.loginw.geometry("500x500")
self.signin = Button(self.loginw,width=20, text="Register", command=self.register)
self.signin.place(relx=0.5, rely=0.5, anchor=CENTER)
def register(self):
self.loginw.quit()
win = Toplevel()
Register(win)
w=Login()
w.loginw.mainloop()
register.py
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
class Register:
def __init__(self):
self.reg = Tk()
self.reg.title("Register")
self.reg.geometry("500x500")
self.revert = Button(self.reg,width=20, text="Return to Login")
self.revert.place(relx=0.5, rely=0.5, anchor=CENTER)
The error raised up after clicking the Register button
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\me\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "c:\Users\me\Documents\Education\Testing code\login.py", line 18, in register
Register(win)
TypeError: Register.__init__() takes 1 positional argument but 2 were given
Thank you so much.
When you are calling the Register class's constructor to get a window, you pass the Toplevel instance named win but within the __init__ method of the Register class you are not accepting any arguments to the constructor.
This can be fixed, by accepting another argument in the __init__ method. Further note there is no need to initialize self.reg as tkinter.Tk() then as the Toplevel instance taken as argument will work in it's place.
The Register class definition will change to -:
class Register:
def __init__(self, win):
self.reg = win # new.
self.reg.title("Register")
self.reg.geometry("500x500")
self.revert = Button(self.reg,width=20, text="Return to Login")
self.revert.place(relx=0.5, rely=0.5, anchor=CENTER)
self.reg.mainloop() # new.
Further, Now a new mainloop has to be started for the new window initalized, thus the line self.reg.mainloop() was added.
With the suggested changes in place, the output seems to be as required by the OP -:
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a function which when called, Doesn't work while other functions in the same indentation work perfectly
This is the function
I've tried a lot of things but they don't seem to work
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter.ttk import Progressbar
from tkinter import messagebox
import tkinter.font as font
import mysql.connector as mys
import time
from time import sleep
def Assign():
# TE Text Entry
# TEfn Text Entry Flight number
# TEp Text Entry Passengers
# TEa Text Entry Airport
# TEd Text Entry Distance
def computing():
master=Tk()
master.title('AMAS')
photo=PhotoImage(file='AMAS.gif') #Image must be GIF
Label(image=photo) # Line required to prevent python's garbage dump function
Label(master,image=photo,fg='black',bg='black').grid(row=0,column=0,sticky=E)
master.resizable(0,0) # Optional line to prevent the user from resizing the window
master.mainloop()
def dwindow():
print('dwindow called')#TEMP
def saveTEd():
global Ed
Ed=TEd.get()
print(Ed)
window.destroy()
# Window Number 5 Called Below
computing()
window=Tk()
window.title("Distance")
window.configure(background='white')
photo1=PhotoImage(file='Distance.gif')
Label(image=photo1)
Label(window,image=photo1,bg='white').grid(row=0,column=0,sticky=W)
Label(window,text='Enter The Distance Travelled',bg='white',fg='black',font='none 12 bold').grid(row=1,column=0,sticky=W)
TEd=Entry(window,width=20,bg='white')
TEd.grid(row=2,column=0,sticky=W)
Button(window,text='Enter',width=6,command=saveTEd).grid(row=3,column=0,sticky=W)
mainloop()
def awindow():
print('awindow called')#TEMP
def saveDDMo(value):
global DDMo
DDMo=aoption.get()
print(DDMo)
window.destroy()
# Window Number 4 Called Below
dwindow()
window=Tk()
window.title("Destination Airport")
window.configure(background='white')
photo1=PhotoImage(file='airport.gif')
Label(image=photo1)
Label(window,image=photo1,bg='white').grid(row=0,column=0,sticky=W)
Label(window,text='Enter The Destination',bg='white',fg='black',font='none 12 bold').grid(row=1,column=0,sticky=W)
OPTIONS = ['Select an option','BNE','MEL','SYD','BAH','BRU','YYZ','PEK','PVG','CAI','MUC','ATH','AMD','BLR','DEL','COK','CCU','CCJ','BOM','TRV','CGK','NBO','KWI','LHR','MAN','ORG','LAX','JFK','DCA']
aoption = StringVar(window)
aoption.set(OPTIONS[0]) # default value
OptionMenu(window, aoption, *OPTIONS,command=saveDDMo).grid(row=2,column=0,sticky=W)
mainloop()
def pwindow():
print('pwindow called')#TEMP
def saveTEp():
global Ep
Ep=TEp.get()
print(Ep)
window.destroy()
# Window Number 3 Called Below
awindow()
window=Tk()
window.title("Passengers")
window.configure(background='white')
photo1=PhotoImage(file='passengers.gif')
Label(image=photo1)
Label(window,image=photo1,bg='white').grid(row=0,column=0,sticky=W)
Label(window,text='Enter The Number Of Passengers',bg='white',fg='black',font='none 12 bold').grid(row=1,column=0,sticky=W)
TEp=Entry(window,width=20,bg='white')
TEp.grid(row=2,column=0,sticky=W)
Button(window,text='Enter',width=6,command=saveTEp).grid(row=3,column=0,sticky=W)
mainloop()
def fnwindow():
def saveTEfn():
global Efn
Efn=TEfn.get()
print(Efn)
window.destroy()
# Window Number 2 Called Below
pwindow()
window=Tk()
window.title("Flight Number")
window.configure(background='white')
photo1=PhotoImage(file='flightnumber.gif')
Label(image=photo1)
Label(window,image=photo1,bg='white').grid(row=0,column=0,sticky=W)
Label(window,text='Enter the Flight Number',background='white',foreground='black',font='none 12 bold').grid(row=1,column=0,sticky=W)
TEfn=Entry(window,width=20,bg='white')
TEfn.grid(row=2,column=0,sticky=W)
Button(window,text='Enter',width=6,command=saveTEfn).grid(row=3,column=0,sticky=W)
Label.pack()
mainloop()
# Window Number 1 Called below
fnwindow()
#The error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\vinayak\AppData\Local\Programs\Thonny\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\vinayak\Documents\Programs 12th\Project.py", line 414, in Assign
fnwindow()
File "C:\Users\vinayak\Documents\Programs 12th\Project.py", line 406, in fnwindow
Label(window,image=photo1,bg='white').grid(row=0,column=0,sticky=W)
File "C:\Users\vinayak\AppData\Local\Programs\Thonny\lib\tkinter\__init__.py", line 2766, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\vinayak\AppData\Local\Programs\Thonny\lib\tkinter\__init__.py", line 2299, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage2" doesn't exist
I think it might be because of what I'm importing or garbage dump but I can't seem to resolve the issue.
I think it might be because of what I'm importing or garbage dump but I can't seem to resolve the issue.
I think it might be because of what I'm importing or garbage dump but I can't seem to resolve the issue.
The error here is image "pyimage2" doesn't exist
Have you tried refering to this? StackOverflow-'image “pyimage2” doesn't exist'?
In short, You can't have two instances of Tk() running simultaneously, you have to use Toplevel() instead.
I'm trying to learn tkinter gui in python 3.7, I have this code:
from tkinter import *
# Configuración de la ventana principal
root=Tk()
root.title("Cath Config")
#Definición de clases
#Frames
class marco(Frame):
def __init__(self, master=None, color="#F3F3F3", ancho="1024", alto="680", borde="5", tipoborde="groove"):
Frame.__init__(self)
self.master=master
self.config(bg=color,width=ancho,height=alto,bd=borde,relief=tipoborde)
self.pack()
#Configuración del widget frame
mainframe1=marco(master="root")
#Ejecución de la ventana principal
root.mainloop()
The problem is the code "works", when I run that code it shows the root with the main frame without problem, but when i attempt to close the root, it does not closes and throws this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\konoe\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\konoe\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2061, in destroy
for c in list(self.children.values()): c.destroy()
File "C:\Users\konoe\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2306, in destroy
if self._name in self.master.children:
AttributeError: 'str' object has no attribute 'children'
The problem is that you've passed a string as the value of the master parameter. That parameter must be a widget, not a string.
mainframe1=marco(master=root)
You should also pass that parameter to the __init__ method:
Frame.__init__(self, master)
Strictly speaking, it's not necessary for this specific code, since the default for the master is the root window. However, if you're going to create a subclass of Frame you should always include the master in the constructor so that the widget can be used in places other than the root window.
One way to handle this is bind the key with the action:
def quit(event):
print "you pressed control c"
root.quit()
root = tk.Tk()
root.bind('<Control-c>', quit)
root.mainloop()
Another way would be to but a Quit button to safely close the Tkinter window.
root=Tk()
root.title("Cath Config")
Button(root, text="Quit", command=quit).pack()
def quit():
global root
root.quit()
I am working with Tkinter in Python 3.5 and I encounter a weird problem.
I used the tkinterbook about events and bindings to write this simple example:
from tkinter import *
root = Tk()
frame = Frame(root, width=100, height=100)
def callback(event):
print("clicked at", event.x, event.y)
# frame.unbind("<Button-1>", callback)
frame.bind("<Button-1>", callback)
frame.pack()
root.mainloop()
It works fine, but if I try to unbind the callback (just uncomment the line), it fails with the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Delgan\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:\Users\Delgan\Desktop\Test\test.py", line 9, in callback
frame.unbind("<Button-1>", callback)
File "C:\Users\Delgan\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 1105, in unbind
self.deletecommand(funcid)
File "C:\Users\Delgan\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 441, in deletecommand
self.tk.deletecommand(name)
TypeError: deletecommand() argument must be str, not function
This is not clear, I am not sure if it is a bug in tkinter or if I am doing something wrong.
frame.unbind("<Button-1>") works fine but I would like to remove this exact callback instead of a global remove.
The second argument to unbind is a 'funcid', not a function. help(root.unbind) returns
unbind(sequence, funcid=None) method of tkinter.Tk instance.
Unbind for this widget for event SEQUENCE the function identified with FUNCID.
Many tk functions return tk object ids that can be arguments for other funtions, and bind is one of them.
>>> i = root.bind('<Button-1>', int)
>>> i
'1733092354312int'
>>> root.unbind('<Button-1>', i) # Specific binding removed.
Buried in the output from help(root.bind) is this: "Bind will return an identifier to allow deletion of the bound function with unbind without memory leak."
I have the following code:
from Tkinter import *
from urllib import urlretrieve
import webbrowser
import ttk
def get_latest_launcher():
webbrowser.open("johndoe.com/get_latest")
global percent
percent = 0
def report(count, blockSize, totalSize):
percent += int(count*blockSize*100/totalSize)
homepage = "http://Johndoe.com"
root = Tk()
root.title("Future of Wars launcher")
Button(text="get latest version", command=get_latest_launcher).pack()
global mpb
mpb = ttk.Progressbar(root, orient="horizontal", variable = percent,length="100",
mode="determinate")
mpb.pack()
root.mainloop()
urlretrieve("https://~url~to~my~file.com",
"Smyprogram.exe",reporthook=report)
however, if I run this script, it won't display the progressbar, and it will only display the button. It wont even download the file, and the cursor will just blink. However, if I close the gui window, I get the following code:
Traceback(most recent call last):
File "C:\Users\user\Desktop\downloader.py", line 28 in <module>
mpb = ttk.Progressbar(root, orient="horizontal", variable =
percent,length="100",mode="determinate")
File "C:\Users/user\Desktop\pyttk-0.3\ttk.py" line 1047, in __init__
Widget.__init__(self, master, "ttk::progressbar", kw)
File "C:\Users/user\Desktop\pyttk-0.3\ttk.py", line 574, in __init__
Tkinter.Widget.__init__(self, master, widgetname, kw=kw)
File "C:\Python26\lib\lib-tk\Tkinter.py", line 1930, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: this isn't a Tk applicationNULL main window
What's wrong?
You have at least two problems in your code, though neither of them cause the error you say you're getting.
First, you use a normal python variable as the value of the variable attribute of the progress bar. While this will work, it won't work as you expect. You need to create an instance of a tkinter StringVar or IntVar. Also, you'll need to call the set method of that instance in order for the progressbar to see the change.
Second, you should never have code after the call to mainloop. Tkinter is designed to terminate once mainloop exits (which typically only happens after you destroy the window). You are going to need to move the call to urlretrieve somewhere else.
variable = percent is wrong. You must use Tkinter Variables which are objects. Such as IntVar.