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

2024-05-03 12:30:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为我的项目实现一个非常简单的GUI。我以前只使用Print语句来输出一些文本和数据。然而,这不是很方便,因为一个人需要操作我正在编码的设备,他需要清楚地看到我将在GUI上显示的指令

我的代码:

main()
myConnection = mysql.connector.connect( host=hostname, user=username, passwd=password, db=database )
counter = 0

window = 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窗口

首先,我不确定应该在哪里调用函数window.mainloop()

其次,由于我的系统运行在一个无限的while循环中(当用户扫描条形码时操作开始,然后他完成一个操作,while循环再次开始(等待用户扫描条形码)。所以我只需显示一些文本,并允许用户在文本框中输入数据

有人能告诉我这个GUI是否适合我的需要,或者我应该寻找替代方案吗

更新************************

我已尝试使用mainloop:

print ("Using mysql.connector…")
main()
GPIO_SETUP() 
myConnection = mysql.connector.connect( host=hostname, user=username, passwd=password, db=database )
counter = 0
window = tk.Tk()
window.resizable(False,False)
window_height = 1000
window_width = 1200
#window.attributes('-fullscreen',True)
#window.config(height=500,width=500)
#can = Canvas(window,bg='red',height=100,width=100)
#can.place(relx=0.5,rely=0.5,anchor='center')
window.title("GUI")
screen_width = window.winfo_screenwidth()
screen_height= window.winfo_screenheight()
x = int((screen_width/ 2) - (window_width / 2))
y = int((screen_height/ 2) - (window_height / 2))   
window.geometry("{}x{}+{}+{}".format(window_width,window_height,x,y))
label1=Label(window,text = "SKENUOKITE BARKODA(GUID) ARBA DAIKTO RIVILINI KODA:")
label1.pack()
entry = Entry(window)
entry.pack()
var = tk.IntVar()
button = Button(window,text="Testi operacija",width = 30,command = lambda: var.set(1))
button.pack()
#button2 = Button(window,text="RESTARTUOTI SISTEMA",width = 30,command = restart_devices())
#button2.pack()
print("waiting...")    
button.wait_variable(var)
Scanned_serial = entry.get()
print("Entry string=",Scanned_serial) 
var.set(0)
label2=Label(window,text = "Vykdoma operacija:")
label2.pack()
window.update()
window.after(1000,Full_operation(Scanned_serial,label2,window))
window.mainloop()

这是我的代码。如您所见。我调用Full_操作函数,然后调用window.mainloop()

我的全面行动:

def Full_operation(Scanned_serial,label2,window):
    operacijos_kodas=Scanning_operation(myConnection,Scanned_serial)
    print("operacijos kodas=",operacijos_kodas)
    if(operacijos_kodas == 0):

        label2.config(text = "SPAUSKITE MYGTUKA ANT DEZES KURIA NORITE PILDYTI:")#update the label2
        window.update()#call update to update the label
        pildymo_operacija(myConnection,Scanned_serial,label2,window)
        
    elif(operacijos_kodas == 1):
        insertData_komplektacija(myConnection,"fmb110bbv801.csv");
        update_current_operation(myConnection);
        #label2.config(text = "IMKITE DAIKTUS IS ZALIOS DEZUTES:")#update the label2
        picking_operation(myConnection,label2);
        
    elif(operacijos_kodas == 2):
        print("Skenuokite dar karta")
        label2.config(text = "NUSKENUOTAS NEGALIMAS KODAS:")#update the label2
        window.update()#call update to update the label

如何确保每次输入完整的操作功能时,我都会再次从干净的GUI启动并启动另一个操作

现在我可以完成一次操作了。之后,GUI没有响应。 我在full_操作开始时添加了一个print语句,它在我完成一次之后不会执行,因此我的主窗口似乎无法正常工作


Tags: textvarupdateguiwindowwidthoperationpack
1条回答
网友
1楼 · 发布于 2024-05-03 12:30:43

您需要调整代码以使用GUI。在tkinter GUI中引入无限循环不会导致各种问题

Mainloop只能调用一次

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

例如,如果您调用函数scan,您将使用

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

相关问题 更多 >