I'm relatively new to python, so please bear with me.
My question has two aspects:
First, I'm trying to make a GUI that randomly pops different sentences to the user, every time in a new frame.
Second, I want the user to be able to close the GUI without stopping the script, like if it was running in the background.
here is my code:
import Tkinter as tk
import random
number = random.randint(0,13)
sentence = {contains 13 sentences
}
window = tk.Tk()
window.output = tk.Label(text = sentence[number])
window.title("I Always See You")
window.geometry("300x150")
def next():
rand= random.randint(0, 13)
window2 = tk.Tk()
window2.output = tk.Label(text = sentence[rand])
window2.output.pack(side="top", fill="x", expand=True)
window2.title("I Always See You")
window2.geometry("300x150")
window.output.pack(side="top", fill="x", expand=True)
choice()
window.after(1000, next)
window.mainloop()
My problem: when my second frame pops, there isn't any text showing, and if it does have something popping, it appears in the first frame.
also, how can you insert a random float in .after() ?
Thank you so much for your help!
cheers
You do not see the text in the second window because Tkinter cannot handle two main windows. You need to use the Toplevel
class for the others. In addition, you haven't specified the parent of the label in next
, so it will probably be packed inside window
instead of window2
.
In addition, you need 14 sentences because randint
, unlike randrange
includes both end points.
To set a random time in after
, just use randint
because it expects an integer number of ms.
To achieve what you want I suggest you to create a main window that will be withdraw (it will run in the background). Then popup Toplevels with random sentences. You need to call again after
inside the next
function if you want the windows to keep poping up. To prevent the after
to be cancelled if the user closes the Toplevel, I called the after
method from the withdrawn main window:
import Tkinter as tk
import random
number = random.randint(0,13)
sentence = {i: str(i) for i in range(14)}
def next():
rand=random.randint(0, 13)
window2 = tk.Toplevel(root)
window2.output = tk.Label(window2, text=sentence[rand])
window2.output.pack(side="top", fill="x", expand=True)
window2.title("I Always See You")
window2.geometry("300x150")
tps = random.randint(1000, 10000)
root.after(tps, next)
root = tk.Tk()
root.withdraw() # hide root window
window = tk.Toplevel(root)
window.output = tk.Label(window, text=sentence[number])
window.title("I Always See You")
window.geometry("300x150")
window.output.pack(side="top", fill="x", expand=True)
tps = random.randint(1000, 10000)
root.after(tps, next)
root.mainloop()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.