这是我的密码。它按我所希望的方式工作,但我总是被告知使用全局变量是糟糕的编码实践,它们可能会导致问题,尽管我不知道如何在不使用它们的情况下更改标签。感谢您的帮助
import tkinter as tk
from tkinter import filedialog, Text
import os
status = 'Start'
startStopBG = 'light green'
def main():
root = configure_screen()
root.mainloop()
def configure_screen():
root = tk.Tk()
root.title('APP')
root.config(bg='snow3')
root.minsize(700, 700)
browse_button = tk.Button(root, text='Browse', width='10', command=browse)
browse_button.place(x=605, y=10)
global text
text = tk.Text(root, height=1.3, width=73)
text.insert(tk.END, 'Enter Path to Storage HERE')
text.place(x=10, y=13)
global start_stop
start_stop = tk.Button(root, height=1, width=12, text=status, bg=startStopBG,
font=('Helvetica', '40'), command=start_scanning)
start_stop.pack(pady=50)
return root
def browse():
path = filedialog.askdirectory(initialdir='/', title='Select where you want to save your file')
text.delete('1.0', tk.END)
text.insert(tk.END, path)
def start_scanning():
global status
global startStopBG
global start_stop
if status == 'Start':
status = 'Stop'
startStopBG = 'red'
else:
status = 'Start'
startStopBG = 'light green'
start_stop.config(text=status, bg=startStopBG)
if __name__ == '__main__':
main()
首先,您可以在主窗口中使用类,而不是使用全局变量,您可以使用类变量。第二,我建议您使用tkinter变量来存储来自widget的重要数据,因为路径和状态。例如,如果使用
text=tk.StringVar()
,则可以使用text.set('value')
或text.get()
从文本中设置或获取值。Tkinter变量是对象,如果您在main中定义了一个对象,则可以在函数中作为全局变量访问它,而无需使用global
。但是,在您的代码中,要将text
用作StringVar
,您应该将Text
小部件更改为Entry
小部件,这更合适,因为path是单个条目值而不是文本。同样,您可以将start_stop
按钮更改为Checkutton
,这将使颜色更改变得不必要,因为您可以为background
和selectcolor
定义颜色下面的代码包括我在此建议的所有更改:
将tkinter作为tk导入 从tkinter导入文件对话框,文本 导入操作系统
据我所知,你想更换标签
试试这个:
通过在主循环中创建函数,您无需执行全局操作和所有操作
相关问题 更多 >
编程相关推荐