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.
Related
Hello I am working on a screenshot related python project using tkinter.
In my program I have a second window opened by a button press code below.
#Opens the second window
def open_win2():
global sec_window
sec_window = Toplevel()
sec_window.config(height = 1800,width = 1800, bg = "chocolate1")
sec_picture_box = Label(sec_window,height=800, width=800, image=mainview)
sec_picture_box.place(x=800, y=100)
I want to create a function that when called will create a button in the second window.
Is this remotely possible. I have tried to do the most simple thing I could think of to test if it can be done (Open a lable when called) the code for the function is which is the command of a button on the root window
def create_secondwindow_button():
screenshot_snap = Label(text = "dog",)
screenshot_snap.grid(sec_window,column = 1, row = 1)
I just get the error message
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Link\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/Link/PycharmProjects/Helloworld/main.py", line 67, in create_secondwindow_button
screenshot_snap.grid(sec_window,column = 1, row = 1)
File "C:\Users\Link\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2226, in grid_configure
+ self._options(cnf, kw))
_tkinter.TclError: bad option "-bd": must be -column, -columnspan, -in, -ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky
Process finished with exit code 0
If you cant do this do you have to imbed your function within the function that opens the second window?
Thanks a bunch for any help!
This is how the function should be:
def create_secondwindow_button():
screenshot_snap = Label(sec_window, text="dog")
screenshot_snap.grid(column=1, row=1)
Also there is no space between kwarg arguments as You can see in my code (per PEP 8 at least).
Also also if You wanted to create a button, it should be:
def create_secondwindow_button():
screenshot_snap = Button(sec_window, text="dog")
screenshot_snap.grid(column=1, row=1)
And just in case You do, don't do this:
from tkinter import *
It is bad practice in general and You should either import what you need:
from tkinter import Tk, Label, Button
Or import the module like this
import tkinter
or
import tkinter as tk
(for example You can use as as You need for example You might as well say as kinter or sth)
In such case You would need to refer like this:
tk.Button
tk.Label
And so on...
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 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.
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 am trying to simultaneously read data from a HID with pywinusb and then update a tkinter window with that data. When something happens on the HID side, I want my tkinter window to immediately reflect that change.
Here is the code:
import pywinusb.hid as hid
from tkinter import *
class MyApp(Frame):
def __init__(self, master):
super(MyApp, self).__init__(master)
self.grid()
self.setupWidgets()
self.receive_data()
def setupWidgets(self):
self.data1 = StringVar()
self.data1_Var = Label(self, textvariable = self.data1)
self.data1_Var.grid(row = 0, column = 0, sticky = W)
def update_data1(self, data):
self.data1.set(data)
self.data1_Var.after(200, self.update_data1)
def update_all_data(self, data):
self.update_data1(data[1])
#self.update_data2(data[2]), all points updated here...
def receive_data(self):
self.all_hids = hid.find_all_hid_devices()
self.device = self.all_hids[0]
self.device.open()
#sets update_all_data as data handler
self.device.set_raw_data_handler(self.update_all_data)
root = Tk()
root.title("Application")
root.geometry("600x250")
window = MyApp(root)
window.mainloop()
When I run the code and make the device send data, I get this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python 3.3\lib\tkinter\__init__.py", line 1442, in __call__
return self.func(*args)
File "C:\Program Files\Python 3.3\lib\tkinter\__init__.py", line 501, in callit
func(*args)
TypeError: update_data1() missing 1 required positional argument: 'data'
I guess my question is:
How do I continually update the label with the current data from the HID?
How can I pass the new data to update_data1()?
Edit: Should I be using threading, so that I have one thread receiving data and the mainloop() thread periodically checking for new data? I haven't used threading before, but could this be a solution?
If there is a better way to do this, please let my know.
Thanks!
self.data1_Var.after(200, self.update_data1) is the problem. You need to pass self.update_data1's parameter to self.data1_Var.after (e.g. self.data1_Var.after(200, self.update_data1, some_data)). Otherwise after 200 milliseconds, self.update_data1 will be called without the parameter, causing the error you are seeing.
BTW, why don't directly edit the label's text instead of putting the code in self.update_all_data. It's not clear to me why self.data1_Var.after(200, self.update_data1) is required, because whenever new data is received, update_all_data is called, which calls update_data1 which updates the text.