我創建了一個 tkinter python 計數應用程式,我只想通過單擊一個按鈕來加 1 或減 1。只是一個常規的計數應用程式。我遇到的問題是加 1 總是有效,但是當我想減 1 時,它會自動變成負數。這是我的腳本:
total_count = 0
def count_number():
global total_count
total_count = total_count 1
count_label["text"] = total_count
minus_count = total_count
def minus_number():
global minus_count
minus_count = minus_count - 1
count_label["text"] = minus_count
count_label = Label(root, fg="orange", font="Verdana 150 bold italic")
count_label.pack()
count_label.place(x=810, y=280)
plus_button = Button(root, text=" 1", width=10, fg="purple", command=count_number).place(x=910, y=870)
minus_button = Button(root, text="- 1", width=10, fg="purple", command=minus_number).place(x=910, y=970)
我怎樣才能從同一個數字中加減1?
uj5u.com熱心網友回復:
在該行minus_count = total_count minus_count被賦值為0。total_count所以這些事件按順序發生:
total_count = 0minus_count = 0- plus 被執行,它增加了
total_count,而不是minus_count - 執行減法,從 中減去 1
minus_count,結果是-1
簡單的解決方法是在兩個地方使用相同的變數:
total_count = 0
def count_number():
global total_count
total_count = total_count 1
count_label["text"] = total_count
def minus_number():
global total_count
total_count= total_count- 1
count_label["text"] = total_count
count_label = Label(root, fg="orange", font="Verdana 150 bold italic")
count_label.pack()
count_label.place(x=810, y=280)
plus_button = Button(root, text=" 1", width=10, fg="purple", command=count_number).place(x=910, y=870)
minus_button = Button(root, text="- 1", width=10, fg="purple", command=minus_number).place(x=910, y=970)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/490113.html
上一篇:為什么變數未定義
