带有textvariable的标签未显示

时间:2019-01-25 07:53:05

标签: python variables tkinter

窗口“ root2”中的标签“ totalresults”未显示。我希望每次在第一个窗口中按下按钮时更新该文本标签,并计算这些按钮的按下量。

     #create the window
     root = Tk()
     root2 = Tk()


     #probability calculations
     totalrolls = tk.StringVar()
     amountofrolls = 0

     #update numbers in gui
        def add_num():
        global amountofrolls
        amountofrolls += 1
        totalrolls.set("Amount of rolls made in total: " +str(amountofrolls))


#button functions
def button_press():
  add_num()

#string variable
totalrolls.set("Amount of rolls made in total: " + str(amountofrolls))

#modify second window
todennäköisyys = Label(root2, text="The quantity of results:")
totalresults = Label (root2, textvariable=totalrolls)

todennäköisyys.pack()
totalresults.pack()
#kick off the event loop
    root.mainloop()
    root2.mainloop()

第二个窗口显示标签时,我没有任何错误或任何错误。

1 个答案:

答案 0 :(得分:3)

您不应启动多个Tk()实例。请改用Toplevel()。参见示例:

from tkinter import *

root = Tk()     # create the window
display = Toplevel(root)

#probability calculations
totalrolls = StringVar()
amountofrolls = 0

def add_num():  # update numbers in gui
    global amountofrolls
    amountofrolls += 1
    totalrolls.set("Amount of rolls made in total: " + str(amountofrolls))

def button_press(): # button functions
    add_num()

#string variable
totalrolls.set("Amount of rolls made in total: " + str(amountofrolls))

#modify second window
todennäköisyys = Label(display, text="The quantity of results:")
totalresults = Label (display, textvariable=totalrolls)
todennäköisyys.pack()
totalresults.pack()

# Create button in root window
Button(root, text='Increase number', command=add_num).pack()

#kick off the event loop
root.mainloop()