[英]How to make randomly pop some gui without stopping the script #python 2.7
我对python比较陌生,所以请多多包涵。
我的问题有两个方面:
首先,我试图制作一个GUI,每次在新框架中向用户随机弹出不同的句子。
其次,我希望用户能够在不停止脚本的情况下关闭GUI,就像脚本在后台运行一样。
这是我的代码:
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()
我的问题是:当第二个框架弹出时,没有任何文本显示,并且如果确实有弹出的东西出现在第一个框架中。
另外,如何在.after()中插入随机浮点数?
非常感谢你的帮助!
干杯
您不会在第二个窗口中看到该文本,因为Tkinter无法处理两个主窗口。 您需要将Toplevel
类用于其他类。 另外,您还没有在next
指定标签的父级,因此它很可能打包在window
而不是window2
。
另外,您需要14个句子,因为randint
不同于randrange
包含两个端点。
要在after
设置一个随机时间,只需使用randint
因为它需要整数毫秒。
为了实现您想要的功能,建议您创建一个将退出的主窗口(它将在后台运行)。 然后弹出带有随机句子的“顶级”。 您需要再次拨打after
里面next
,如果你想窗户,保持坡平了功能。 为了防止用户关闭顶层after
取消,我从撤回的主窗口中调用after
方法:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.