我尝试使用IntVar失败,不确定我是否理解正确。
from tkinter import*
import random
Part1 = list(range(1,51))
Part2 = list(range(1,11))
Numbers = [0]*7
for n in range (5):
Number = random.choice(Part1)
Position = Part1.index(Number)
del Part1[Position]
Numbers[n] = Number
for i in range (2):
Number = random.choice(Part2)
Position = Part2.index(Number)
del Part2[Position]
Numbers[5+i] = Number
print (Numbers)
def master1_quit():
master1.destroy()
# def window():
master1 = Tk()
Label(master1, text="Guess numbers:").grid(row=0)
e1 = Text(master1, width=2, height=1)
e2 = Text(master1, width=2, height=1)
e3 = Text(master1, width=2, height=1)
e4 = Text(master1, width=2, height=1)
e5 = Text(master1, width=2, height=1)
e6 = Text(master1, width=2, height=1)
e7 = Text(master1, width=2, height=1)
e1.grid(row=0, column=1, padx=5)
e2.grid(row=0, column=2, padx=5)
e3.grid(row=0, column=3, padx=5)
e4.grid(row=0, column=4, padx=5)
e5.grid(row=0, column=5, padx=5)
e6.grid(row=0, column=7, padx=5)
e7.grid(row=0, column=8, padx=5)
master1.grid_columnconfigure(6, minsize=20) # Creates an empty column (nr. 6) with width 20
# Save guessed numbers
Guess = [e1.get(1.0, "end-1c"), e2.get(1.0, "end-1c"), e3.get(1.0, "end-1c"), e4.get(1.0, "end-1c"), e5.get(1.0, "end-1c"), e6.get(1.0, "end-1c"), e7.get(1.0, "end-1c")]
Button(master1, text='OK', command=master1_quit).grid(row=3, column=3, sticky=W, pady=5)
master1.mainloop()
# window()
基本上,我希望在销毁窗口后保存变量“ Guess”,因为我以后想使用它。
其他问题: 是否可以稍后在代码中编写“ def window()”并使用“ window()”调用该窗口?
答案 0 :(得分:0)
欢迎使用Stackoverflow,并感谢您提出的明确问题。
如果更改master1_quit
函数以在窗口退出时更新全局变量Guess
,则Guess
将显示7个文本小部件的最终状态,如下例所示。创建UI时,您的代码中Guess
是从7个文本小部件中填充的。那时所有“文本”字段均为空。
def master1_quit():
global Guess
Guess = [e1.get(1.0, "end-1c"), e2.get(1.0, "end-1c"), e3.get(1.0, "end-1c"),
e4.get(1.0, "end-1c"), e5.get(1.0, "end-1c"), e6.get(1.0, "end-1c"),
e7.get(1.0, "end-1c")]
master1.destroy()
对于这样简单的数据,您可能会发现Entry小部件比Text小部件更容易。您可以使用e1.get()恢复Entry小部件中的文本,而无需担心任何参数。