我正在努力解决一个看似简单的问题:我希望能够通过手动更改条目的值来更新tkinter
中进度条的最大值。会发生什么是初始值100不会改变。好的,我认为通过在方法set
中调用count
,我可以更新最大值。它没用。有什么问题?
import tkinter as tk
from tkinter import ttk
from time import sleep
class Window():
def __init__(self, master):
self.master = master
self.configure()
self.create_widgets()
def configure(self):
self.master.title('Progress bar')
self.master.minsize(height=100, width=500)
def create_widgets(self):
self.progress = tk.DoubleVar()
self.number = tk.StringVar()
self.number.set('100')
self.max = tk.IntVar()
self.max.set(eval(self.number.get()))
b1 = tk.Button(self.master, text='Count!', command=self.count)
b1.pack()
e1 = tk.Entry(self.master, textvariable=self.number, width=5)
e1.pack()
p = ttk.Progressbar(self.master, orient='horizontal', length=200, mode='determinate', variable=self.progress, value=1, maximum=self.max.get())
p.pack()
def count(self):
self.max.set(eval(self.number.get()))
for i in range(eval(self.number.get())):
sleep(0.01)
print(i)
self.progress.set(i)
self.master.update()
def main():
root = tk.Tk()
app = Window(root)
root.mainloop()
main()
答案 0 :(得分:1)
你可能会因为你的问题过于复杂而挣扎。当您需要 none 时,为什么要使用3个单独的Variable类?目前,您会创建一个静态最大值为100的进度条,然后通过设置条目的值来更改该窗口的进度。
这是一个更新进度条最大值的最小示例:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
import tkinter.ttk as ttk
except ImportError:
import Tkinter as tk
import ttk
class RestartableProgress(tk.Frame):
def __init__(self, master, *args, **kwargs):
tk.Frame.__init__(self, master, *args, **kwargs)
self.max_input = tk.Entry(self)
self.restart_button = tk.Button(self, text="Restart",
command=self.restart)
self.progressbar = ttk.Progressbar(self)
self.max_input.pack()
self.restart_button.pack()
self.progressbar.pack()
def restart(self):
self.progressbar['value'] = 0
self.progress()
def progress(self):
max_val = self.max_input.get()
if max_val:
self.progressbar['maximum'] = int(max_val)
if self.progressbar['value'] < self.progressbar['maximum']:
self.progressbar['value'] += 1
self.after(10, self.progress)
def main():
root = tk.Tk()
rp = RestartableProgress(root)
rp.pack()
tk.mainloop()
if __name__ == '__main__':
main()