简体   繁体   English

有没有更有效的方法来更新 tkinter 上的标签?

[英]Is there a more efficient way to update labels on tkinter?

Here is my code.这是我的代码。 It works how I want it to but I have always been told it is poor coding practice to use global variables and that they can cause problems, although I cannot figure out how to get the labels to change without using them.它可以按我的意愿工作,但我一直被告知使用全局变量是不好的编码习惯,并且它们可能会导致问题,尽管我无法弄清楚如何在不使用它们的情况下更改标签。 Any help is appreciated.任何帮助表示赞赏。

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()

First of all you can use a class to your main window and instead of global variables you use class variables.首先,您可以使用 class 到您的主要 window ,而不是使用全局变量 class 变量。 Second I would recommend you to use tkinter variables to store important data from widget since the path and the status.其次,我建议您使用 tkinter 变量来存储来自小部件的重要数据,因为路径和状态。 For example, if you use text=tk.StringVar() you can set or get the value from text with text.set('value') or text.get() .例如,如果您使用text=tk.StringVar()您可以使用text.set('value')text.get()从文本中设置或获取值。 Tkinter variables are object and if you define an object in your main you can access it as a global variable inside functions without the need of using global . Tkinter 变量是 object ,如果您在 main 中定义 object ,您可以将其作为函数内部的全局变量访问,而无需使用global However, in your code, to use text as a StringVar you should change the Text widget for an Entry widget, which is more appropriated since path is a single entry value and not a text.但是,在您的代码中,要将text用作StringVar ,您应该将Text小部件更改为Entry小部件,这更合适,因为 path 是单个条目值而不是文本。 The same way you can change your start_stop button to a Checkutton and it will make the color change unnecessary since you can define colors for background and selectcolor .与您可以将start_stop按钮更改为Checkutton的方式相同,这将使颜色更改变得不必要,因为您可以为backgroundselectcolor

The code bellow includes all changes I suggest here:下面的代码包括我在这里建议的所有更改:

import tkinter as tk from tkinter import filedialog, Text import os从 tkinter 导入 tkinter 作为 tk 导入文件对话框,文本导入 os

class Main(tk.Tk):
    def __init__(self):
        super(Main, self).__init__()
        self.title('APP')
        self.config(bg='snow3')
        self.minsize(700, 700)

        self.status = tk.IntVar()
        self.text = tk.StringVar(self, value='Enter Path to Storage HERE')

        browse_button = tk.Button(self, text='Browse', width='10', 
                                  command=self.browse)
        browse_button.place(x=605, y=10)

        tk.Entry(self, width=73, textvariable=self.text).place(x=10, y=13)

        self.start_stop = tk.Checkbutton(self, height=1, width=12, text="start", 
                                    font=('Helvetica', '40'), indicator=False, 
                                    bg='light green', selectcolor='red', 
                                    variable=self.status, command=self.start_scanning)
        self.start_stop.pack(pady=50)

    def browse(self):
        path = filedialog.askdirectory(initialdir='/', title='Select where you want to save your file')
        self.text.set(path)

    def start_scanning(self):
        if self.status.get():
            self.start_stop.config(text='stop')
        else:
            self.start_stop.config(text='start')


if __name__ == '__main__':
    Main().mainloop()

As I understood you want to change label据我了解,您想更改 label

Try This:尝试这个:

import tkinter as tk

def main():

    def change_label_text():
        mylabel.config(text="yeee My Text has Been changed")

    def change_button_text():
        mybutton.config(text="yee Button text has been changed")

    root = tk.Tk()
    root.title('Change Label')
    root.config(bg='snow3')
    root.geometry('400x300')

    mybutton = tk.Button(root, text='Press Me To Change Button Text', command=change_button_text)
    mybutton.pack(side='top')

    mylabel = tk.Label(root, text='Press The Button Above To Change My text')
    mylabel.pack(side='bottom')

    mybutton2 = tk.Button(root, text="Press me", command=change_label_text)
    mybutton2.pack(side='bottom')
    root.mainloop()

main()

By making functions inside the mainloop you dont need to do global stuff and all通过在主循环中创建函数,您不需要做全局的事情和所有

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM