为了账号安全,请及时绑定邮箱和手机立即绑定

Python如何在不干扰主代码循环的情况下使用Tkinter GUI

Python如何在不干扰主代码循环的情况下使用Tkinter GUI

慕慕森 2023-06-27 13:46:12
我想为我的项目实现一个非常简单的 GUI。我以前只使用 Print 语句来输出一些文本和数据。然而,这不是很方便,因为一个人需要操作我正在编码的设备,所以他需要清楚地看到我将在 GUI 上显示的指令。我的代码:main()myConnection = mysql.connector.connect( host=hostname, user=username, passwd=password, db=database )counter = 0window = tk.Tk()window.title("GUI")window.geometry("400x200")while(1):    # OPERACIJOS KODAI:    # 0 - PILDYMAS    # 1 - KOMPLEKTAVIMAS    # 2 - NETINKAMAS KODAS    tk.Label(window,text = "Scan barcode here:").pack()    entry = tk.Entry(window)    entry.pack()    var = tk.IntVar()    button = tk.Button(window,text="Continue",command = lambda: var.set(1))    button.pack()    print("waiting...")    button.wait_variable(var)    result = entry.get()    print("Entry string=",result)    var.set(0)        operacijos_kodas=Scanning_operation(myConnection,result)    print("operacijos kodas=",operacijos_kodas)    if(operacijos_kodas == 0):        tk.label(window,text = "PILDYMO OPERACIJA:").pack()        pildymo_operacija(myConnection)               elif(operacijos_kodas == 1):        tk.Label(window,text = "PAKAVIMO OPERACIJA:").pack()        insertData_komplektacija(myConnection,"fmb110bbv801.csv");        update_current_operation(myConnection);        picking_operation();            elif(operacijos_kodas == 2):        print("Skenuokite dar karta")        #break   window.mainloop();没有显示任何内容。它只是打开一个空的 GUI 窗口。首先,我不确定应该在哪里调用 function window.mainloop()。其次,由于我的系统在无限的 while 循环中运行(当用户扫描条形码时操作开始,然后他完成操作并且 while 循环再次开始(等待用户扫描条形码)。所以我只需要显示一些文本并允许用户在文本框中输入数据。有人可以建议我这个 GUI 是否适合我的需求,或者我应该寻找替代品吗?
查看完整描述

1 回答

?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

您需要调整代码以与 GUI 配合使用。您无法在 tkinter GUI 中引入无限循环而不引起各种问题。


Mainloop 应该只被调用一次。


我建议您将所有扫描/保存操作移至一个单独的函数中,您计划使用 tkinterafter方法定期执行该函数。


例如,如果您调用函数,scan您可以使用以下命令将其安排在 1 秒后发生


root.after(1000, scan)

更高级的方法是让扫描代码在单独的线程上运行。


此外,您当前尝试在每次循环 while 循环时创建标签,而不是仅创建和打包它们一次并在执行“扫描”时更新标签的文本。您可以使用 config 方法更新标签的文本,例如


## Create a label

label1 = tk.Label(window,text = "PAKAVIMO OPERACIJA:")

##Pack the label

label1.pack()


## Update the text later

label1.config(text="New Text")

以下是从函数定期更新 tkinter 小部件的示例。


import tkinter as tk

import random


def scanning():

    num = random.randint(0,100)

    entryTemperature.delete(0, tk.END) #Delete the current contents

    entryTemperature.insert(0, f"{num} K") #Add new text

    root.after(1000, scanning) #Schedule the function to run again in 1000ms (1 second)



root = tk.Tk()

entryTemperature = tk.Entry(root)

entryTemperature.grid(padx=50,pady=50)


root.after(1000, scanning)

root.mainloop()

    


查看完整回答
反对 回复 2023-06-27
  • 1 回答
  • 0 关注
  • 102 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信