將通過說我對 python 和一般編碼非常陌生,我遵循了一個關于如何制作倒數計時器的教程,并設法撰寫了一個按鈕,該按鈕通過將我的代碼搗碎來測量它被點擊的次數我在論壇上找到的帶有帖子的按鈕,倒數計時器在最后顯示一個“超時”訊息框,我想要做的是讓它也顯示在分配的時間內單擊按鈕的次數。我已經嘗試從倒數計時器中呼叫全域計數并重用在 GUI 中顯示計數的行,但這似乎破壞了它并且在沒有它的情況下進行,如此處顯示只顯示寫入的字串,任何幫助或感謝指導
'''
import time
from tkinter import *
from tkinter import messagebox
f = ("Arial",24)
root = Tk()
root.title("Click Counter")
root.config(bg='#345')
root.state('zoomed') #opens as maximised, negating the need for the 'Geometry' command
count = 0
def clicked():
global count
count = count 1
myLabel.configure(text=f'Button was clicked {count} times!!!')
hour=StringVar()
minute=StringVar()
second=StringVar()
hour.set("00")
minute.set("00")
second.set("10")
hour_tf= Entry(
root,
width=3,
font=f,
textvariable=hour
)
hour_tf.place(x=80,y=20)
mins_tf= Entry(
root,
width=3,
font=f,
textvariable=minute)
mins_tf.place(x=130,y=20)
sec_tf = Entry(
root,
width=3,
font=f,
textvariable=second)
sec_tf .place(x=180,y=20)
TheButton = Button(root, height= 30, width=100, bg="light blue", text="Click For Your Life", command=clicked) #tells the button to call the function when clicked
TheButton.pack()
myLabel = Label(root)
myLabel.pack()
def startCountdown():
try:
userinput = int(hour.get())*3600 int(minute.get())*60 int(second.get())
except:
messagebox.showwarning('', 'Invalid Input!')
while userinput >-1:
mins,secs = divmod(userinput,60)
hours=0
if mins >60:
hours, mins = divmod(mins, 60)
hour.set("{0:2d}".format(hours))
minute.set("{0:2d}".format(mins))
second.set("{0:2d}".format(secs))
root.update()
time.sleep(1)
if (userinput == 0):
messagebox.showinfo("Time's Up!!", "you clicked (count) times")
userinput -= 1
start_btn = Button(
root,
text='START',
bd='5',
command= startCountdown
)
start_btn.place(x = 120,y = 120)
root.mainloop()
'''
uj5u.com熱心網友回復:
您需要使用帶有“{}”的 f-String,就像您在clicked函式中所做的那樣:
if (userinput == 0):
messagebox.showinfo(f"Time's Up!! you clicked {count} times")
uj5u.com熱心網友回復:
一個好心的用戶提供了正確的答案,但認為洗掉他們的評論是合適的,所以如果像我這樣的人在舊帖子中尋找幫助,這里是有效的“讓你的訊息框顯示點擊次數(在這種情況下是計數),你可以簡單地使用 messagebox.showinfo("Time's Up!!", "you clicked " str(count) " times") 而不是 messagebox.showinfo("Time's Up!!", "you clicked (count) times") ). 你的嘗試是行不通的, 因為你在引號內包含了 count, 這意味著 Python 將完全忽略 count 也是一個變數的事實, 只是將它列印為字串. 有很多方法可以格式化字串包括變數等。在這里查看一個很好的教程/解釋。” 這是他們鏈接的內容 令人失望的是,他們洗掉了他們的評論,因為它的措辭非常好,很有幫助,所以如果你讀了這篇……謝謝!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338395.html
