【问题标题】:how to make this function work in order with the tkinter label如何使用 tkinter 标签使此功能按顺序工作
【发布时间】:2020-11-03 04:30:47
【问题描述】:

所以我的代码中的函数有问题,它没有在控制台中显示失败,所以我只是不知道出了什么问题。 基本上我试图做一个点击器有点像每次点击按钮时都会将 exp 变量增加一个然后更新标签,但它并没有真正起作用。关卡部分也不需要太多关注,除非你有什么想说的。


window = Tk()

window.title ("test")



#variables
exp2 = 0
level = 1
exp = 0

#exp function
def function ():
    global exp,exp2, level
    exp2 = exp + 1
    if exp <100:
        exp = 0
        level + 1
    else:
        return function()



#labels
label_1 = Label (window, text = (exp2,"/100"), bg = 'white', fg ='black')
label_2 = Label (window, text = "exp" , bg = 'white', fg ='black')
label_3 = Label (window, text = "level", bg = 'white', fg ='black')
label_4 = Label (window, text = level, bg = 'white', fg ='black')

#buttons
button_1 = Button (window, text = 'click for xp', command = function())

#placements
label_1.grid (column = 3, row = 2)
label_2.grid (column = 3, row = 1)
label_3.grid (column = 5 , row = 1)
label_4.grid (column = 5, row = 2)
button_1.grid (column = 4, row = 4 )

window.mainloop()

【问题讨论】:

  • command=function() 应该是command=function(没有())。再想想function()里面的逻辑。

标签: python function tkinter


【解决方案1】:
def Function():
    global exp, level
    exp += 1
    if exp > 100:
        exp=0
        level+=1
    label.config(text=exp)

应该为您工作,您实际上不需要 exp2 变量。 label.config 为您准备好了

【讨论】:

    【解决方案2】:
        #python3
        from tkinter import *
        window = Tk()
        window.title ("test")
    
        #variables
        #exp2 = 0
    
        exp = 0
        level=0
    #exp function
        def function ():
            global exp,exp2, level
            label_1.configure(text="%d" %(exp)+"/10")
            exp+=1
            if exp==10:
                    level+=1
                    label_4.configure(text=level)
                    exp=0
                    
    
         
    
    
    
        #labels
        label_1 = Label (window,text="%d" %(exp)+"/10", bg = 'white', fg ='black')
        label_2 = Label (window, text = "exp", bg = 'white', fg ='black')
        label_3 = Label (window, text = "level", bg = 'white', fg ='black')
        label_4 = Label (window,  bg = 'white', fg ='black')
        #buttons
        button_1 = Button (window, text = 'click for xp', command = function)
        #placements
        label_1.grid (column = 3, row = 2)
        label_2.grid (column = 3, row = 1)
        label_3.grid (column = 5 , row = 1)
        label_4.grid (column = 5, row = 2)
        button_1.grid (column = 4, row = 4 )
    
        window.mainloop()
    

    虽然我不是很明白这个问题,但我希望它回答了你的问题。您可以通过删除 label_1.after(500,function) 来停止连续计数。如果这回答了您的问题,请投票

    【讨论】:

    • 我尝试使用 10 而不是 100。所以当它达到 10 时,级别会更新 1
    • OP 只想在单击按钮时更新explevel。所以after()不应该被使用。
    • 我已经编辑了答案,这能回答你的问题吗?
    猜你喜欢
    • 2018-12-21
    • 1970-01-01
    • 2014-09-27
    • 2015-06-08
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2016-10-04
    相关资源
    最近更新 更多