簡體   English   中英

在Python 3中使用tkinter時,如何在每次按下函數時獲得一個按鈕來運行函數?

[英]When using tkinter in Python 3, how do you get a button to run a function each time it is pressed?

import tkinter as tk
panel = tk.Tk()
num = 42
lbl1 = tk.Label(panel, text = str(num))

假設我有一個像這樣的功能和按鈕:

def increase():
    lbl1.configure(text = str(num+1))

btn = tk.Button(panel, text = 'Increase', command = increase)

panel.mainloop()

按下按鈕時,標簽上的數字將增加1。 但是,此操作僅在按鈕完全不起作用之前起作用一次。 如何使每次按下按鈕時數字增加1?

您從未保存過num的增量值。

def increase():
    global num # declare it a global so we can modify it
    num += 1 # modify it
    lbl1.configure(text = str(num)) # use it

因為num總是43

import tkinter as tk
num = 42

def increase():
    global num
    num += 1
    lbl1.configure(text = str(num))


panel = tk.Tk()

lbl1 = tk.Label(panel, text = str(num))
lbl1.pack()
btn = tk.Button(panel, text = 'Increase', command = increase)
btn.pack()
panel.mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM