带进度条的Tkinter链接按钮

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了带进度条的Tkinter链接按钮相关的知识,希望对你有一定的参考价值。

我正在使用Tkinter创建一个cookie clicker应用程序。我想在我的程序中有一个进度条,每次点击cookie 100次就会填满。我使用import ttk创建了进度条,但是每当按下按钮时我都不知道如何更新进度条。到目前为止,这是我的代码:

from Tkinter import *
from Tkinter import Canvas
import ttk
window1 = Tk()
window1.title("Cookie Clicker")
window1.config(background="dodger blue")
window1.geometry("254x370")
clicks = 0


def cookie_clicks():
    global clicks
    clicks = clicks + 1
    print("{0}".format(clicks))
    if clicks == 1:
        lbl1.configure(text="{0} Cookie!".format(clicks))
    else:
        lbl1.configure(text="{0} Cookies!".format(clicks))


cookie = Button(window1, highlightbackground="dodger blue", borderwidth=0, cursor="hand2", command=cookie_clicks)
photo = PhotoImage(file="imageedit_3_3213999137.gif")
cookie.config(image=photo, width="250", height="250")
cookie.place(x=0, y=90)
w = Canvas(window1, width=254, height=75, highlightbackground="gray")
w.pack()
w.create_rectangle(10, 10, 80, 80, outline="gray", fill="gray", width=100000)
w2 = Canvas(window1, width=0.1, height=250, highlightbackground="dodger blue")
w2.place(x=0, y=85)
w3 = Canvas(window1, width=0.1, height=250, highlightbackground="dodger blue")
w3.place(x=249, y=85)
w4 = Canvas(window1, width=250, height=0.1, highlightbackground="dodger blue")
w4.place(x=0, y=88)
w5 = Canvas(window1, width=250, height=0.1, highlightbackground="dodger blue")
w5.place(x=0, y=338)
lbl1 = Label(window1, bg="gray", fg="dodger blue", text="{0} Cookies!".format(clicks), font=("kavoon", 20))
lbl1.place(x=75, y=45)
lbl2 = Label(window1, bg="gray", fg="dodger blue", text="Cookie Clicker", font=("kavoon", 30))
lbl2.place(x=20, y=0)
pb = ttk.Progressbar(window1, orient='horizontal', mode='determinate')
pb.pack()


window1.mainloop()

任何帮助,将不胜感激!

答案

在不改变代码的情况下,您可以:

def cookie_clicks():
    global clicks, pb
    clicks = clicks + 1
    pb.step(1)
    print("{0}".format(clicks))
    if clicks == 1:
        lbl1.configure(text="{0} Cookie!".format(clicks))
    else:
        lbl1.configure(text="{0} Cookies!".format(clicks))

使用global变量并不好。您应该考虑在一个类中封装您的应用程序。

以上是关于带进度条的Tkinter链接按钮的主要内容,如果未能解决你的问题,请参考以下文章

应用程序 QT 崩溃(带进度条的 ftp 下载)

简洁大气带进度条的URL跳转页面HTML源码

带进度条的文件上传

活动到片段方法调用带有进度条的线程

Tkinter 之ProgressBar进度条标签

Ajax技术——带进度条的文件上传