def meaning(word): #Outside tkinter window
data=open_files()
meaning=data[word]
for each_word in meaning:
result_box.insert(END,each_word)
result_box=" "
print("Result_box initialised") # Inside tkinter window
result_box=Text(window,height=20,width=50,wrap="word")
result_box.grid(row=7,column=2,rowspan=6,columnspan=6,padx=2,pady=2)
Every things working just fine, just when the meaning() is called this Error
shows up. Tried every thing like including the function body inside
window.loop() to make it local to tkinter windows but it didn't seem to work.
Any help will be appreciated. Thanks.
This happens because result_box is not defined inside the function. If it is a global variable, you can write
global result_box
inside the function.
Related
I just started learning Tkinter and when thing that really stood out was
win=tkinter.Tk()
I mean from what it looks win is basically a reference for the main window we created but this is the first time I have seen something like this since tk() is a method and not a class . I know that everything is an object in python eh but I am kinda confused , help me senpais ....
Why do we store methods in a variable when using Tkinter in python?
This question doesn't make much sense. Most programs do not store methods.
Regardless, tkinter is no different than any other module in this regard: you save a reference to something when you need to refer to the object later or you need to prevent the garbage collector from collecting the object.
I mean from what it looks win is basically a reference for the main window we created
That is correct. In your code example win is a reference to the root window, an instance of the Tk class.
I have seen something like this since tk() is a method and not a class
That is not true. At least, not if you meant to say Tk(). Tk from the tkinter module is in fact a class. So in this case you are creating an instance of the Tk class.
tkinter.Tk() is an object of type tkinter.Tk, not a method.
Alright, so I want to make a gif display when a function has been called, but the gif will go invisible and not show up. I searched for possible answers but all of them mention "create a reference to (insert code here)" and I don't really get it because:
1. 99% of them use objects and classes in which I have 0 experience
2. Some say to make a reference with "self.img = PhotoImage(...)" which I'm pretty sure its connected to objects and classes.
3. Others only say to create a reference.
Sorry for being somewhat rude. I'm just really fed up, I searched for answers for 2 hours now.
I tried to assign the variable to global, place the variable in the function and tried to remake the gif and rename the file
This is what I tried to do
def red_flicker():
global root
red_btn_flicker = tk.PhotoImage(file='test.gif')
label_red = tk.Label(image=red_btn_flicker)
label_red.place(x=red_btn_place_x, y=red_btn_place_y)
the gif is invisible.
Please be noob friendly.
Any stuff about python 2.7 and using objects/classes will be ignored
Ok so first things first.
Your function is adding a new label every time it is call so you probably should generate the label in the global namespace once and then just apply the image to the label in the function. This way you can call the function all you want without adding more labels.
I would also move your PhotoImage to the global so you do not need to keep reopening the image each time you load the function.
By making this change we do not even need to use global as the widget creating and image loading happens in the global already.
Make sure to save the reference to the image so its not garbage collected.
import tkinter as tk
root = tk.Tk()
red_btn_flicker = tk.PhotoImage(file='test.gif')
label_red = tk.Label(root)
label_red.pack()
def red_flicker():
label_red.config(image=red_btn_flicker)
label_red.image = red_btn_flicker # saving reference to image.
red_flicker()
root.mainloop()
You must save a reference, as mentioned in the answer to this question: Why does Tkinter image not show up if created in a function?
Since you aren't using classes, you can use a global variable. For example:
def red_flicker():
global red_btn_flicker
red_btn_flicker = tk.PhotoImage(file='test.gif')
label_red = tk.Label(image=red_btn_flicker)
label_red.place(x=red_btn_place_x, y=red_btn_place_y)
Another simple technique is to attach the image as an attribute of the label itself. This works because python lets you create custom attributes on an object. However, you must make sure that the reference to the label itself isn't lost
def red_flicker():
global label_red
red_btn_flicker = tk.PhotoImage(file='test.gif')
label_red = tk.Label(image=red_btn_flicker)
label_red.place(x=red_btn_place_x, y=red_btn_place_y)
label_red.image = red_btn_flicker
I'm trying to create a calculator in Tkinter. Although my current code works well to create the buttons with the correct number on each button since the function is only called after the iteration creating the variables is done, x is always 8, and thus all buttons have a value of 8. How could I circumvent this problem?
I tried without using lambda to call the function, but then the buttons don't even work at all, I'm not really sure why.
Heres the basic code:
from tkinter import *
window=Tk()
ButtonFrame=Frame(window)
ButtonFrame.place(x=100,y=100)
def NumPressed (Digit):
print(Digit)
for y in range(3):
for x in range(3):
NumTXT=y*3+x
Buttonx=Button(ButtonFrame,text=NumTXT,command=lambda:NumPressed(NumTXT))
Buttonx.grid(row=y,column=x)
It has to do with default values in the lambda function. After the buttons are all created the NumTXT variable == 8. Each time you press a button it uses the current value of NumTXT.
You can fix this by giving the lambda function a default value which doesn't change:
command=lambda x=NumTXT: NumPressed(x)
^
# Set default value
then each button will have a lambda function with a default value as NumTXT was at button creation.
I have written some code in python for a live time in tkinter.
Whenever I run the code it comes up with some numbers on the tkinter window like 14342816time. Is there a way to fix this?
import tkinter
import datetime
window = tkinter.Tk()
def time():
datetime.datetime.now().time()
datetime.time(17, 3,)
print(datetime.datetime.now().time())
tkinter.Label(window, text = time).pack()
window.mainloop()
After some fixes to your code, I came up with the following, which should at least get you started toward what you want:
import datetime
import tkinter
def get_time():
return datetime.datetime.now().time()
root = tkinter.Tk()
tkinter.Label(root, text = get_time()).pack()
root.mainloop()
The imports are needed so that your program knows about the contents of the datetime and tkinter modules - you may be importing them already, however, I can't tell that for certain from what you posted. You need to create a window into which you put your label, which wasn't happening; following convention, I called that parent (and only) window "root". Then I put the Label into root. I changed the name of your time() function to get_time(), since it's best to avoid confusing fellow programmers (and maybe yourself) with a function that shares its name with another (the time() function in time). I removed two lines in get_time() that don't actually accomplish anything. Finally, I changed the print you had to a return, so that the value can be used by the code calling the function.
There are other improvements possible here. If you're content with the time as it is, you could eliminate the get_time function and just use datetime.datetime.now().time() instead of calling get_time(). However, I suspect you might want to do something to clean up that time before it is displayed, so I left it there. You might want to research the datetime and time modules some more, to see how to clean things up.
I am trying to make a popup window where someone can fill in a string in an Entry box. I have gone through many examples, but it doesn't work.
I am trying to this:
var_entry = simpledialog.askstring("Test", "Test")
I get this error message:
_tkinter.TclError: window ".!_querystring" was deleted before its visibility changed
Thanks in advance!
edit: posted wrong error message
I know this is an old thread, but I'm having the same problem and so far haven't found the root cause.
However, this workaround works for me in case anyone else needs it:
#Create a new temporary "parent"
newWin = Tk()
#But make it invisible
newWin.withdraw()
#Now this works without throwing an exception:
retVal = simpledialog.askstring("Enter Value","Please enter a value",parent=newWin)
#Destroy the temporary "parent"
newWin.destroy()
I was also able to work around the problem by using the above workaround suggested by John D.
I did some research on this, and it seems that this exception is raised when all of the following conditions are met.
The thread that called the simpledialog.askstring method is not the main thread.
The Tk window specified in the parent or the Tk window specified in the default_root variable is different from the thread that called the simpledialog.askstring method.
However, I could not come up with a process to deal with this problem. I hope this helps to solve the problem.
This issue is caused by askstring is not called in the main thread, which is the main thread.
Make sure to call this method in the main thread. For example, this code works well.
from tkinter import Tk
from tkinter.simpledialog import askstring
a = Tk()
askstring('1', '2')
a.mainloop()
And this code will throw your exception when you close the dialog window.
from tkinter import Tk
from tkinter.simpledialog import askstring
from threading import Thread
a = Tk()
Thread(target=askstring, args=('1', '2')).start()
a.mainloop()
I'm not sure without your code example but I figured that this error message means that the variable where you are putting the 'askstring' return value or initialvalue is going out of scope before the dialog window is finished.
When I had this error message I placed a declaration of the variables outside the inner scope. Forgive me if I am talking here using C concepts (which most Python users would rather ignore).
answer = "dummy"
query_str = "dummy" # without these lines query_str and answer
# can be cleaned up by Python
# before the 'askstring' is done with them
while (1):
query_str = "0"
answer = simpledialog.askstring("Get Number",
"Enter NextNumber",
initialvalue = query_str)
print(answer)
print(query_str)
time.sleep(1)
Adding the declarations outside the loop scope worked for me.