我正在使用 tkinter 在 python 中構建一個專案但是在 tkinter 中使用多個視窗時,我遇到了一個問題,在我的代碼中,您可以在下面看到,在我的第一個視窗中,通過按打開輸入框按鈕,我可以打開我的第二個視窗從那里我想使用Entry box來獲取值以存盤在本地資料庫中,但是每當我嘗試這樣做時,每次它回傳一個空字串。但它在一個視窗中作業,雖然從這段代碼中我已經給出了我想要實作的簡要想法
from tkinter import *
import pymysql
class Sample():
def __init__(self,root):
self.root = root
self.root.geometry("200x200")
S_Button = Button(root,text="Open entry Box",command=self.add).pack()
def add(self):
self.second = Tk()
self.second.geometry("500x200")
self.SRN = StringVar()
S_entry = Entry(self.second,textvariable=self.SRN).pack()
S_Button2 = Button(self.second,text="Store in Database",command=self.data).pack()
self.second.mainloop()
def data(self):
print(self.SRN.get())
#con = pymysql.connect(host="localhost",user="root",password="",database="stm")
# cur = con.cursor()
# cur.execute("insert into StudentsData value (%s),(self.SRN.get()))
# con.commit()
# con.close()'''
uj5u.com熱心網友回復:
您的問題是您正在使用Tk(). 這樣做意味著您有兩個單獨的Tk()運行實體,它們基本上不能相互互動(可以在此處找到對此的一個很好的解釋)。因此,為什么您無法將Entry框中的文本存盤在其中StringVar并且它只回傳一個空字串。相反,使用Toplevel(). 它做你想做的事,而只使用一個Tk()。作業示例使用Toplevel:
import tkinter as tk
class Sample():
def __init__(self,root):
self.root = root
self.root.geometry("200x200")
S_Button = tk.Button(root,text="Open entry Box",command=self.add)
S_Button.pack()
def add(self):
self.second = tk.Toplevel(self.root)
self.second.geometry("500x200")
# Widgets, StringVar
self.SRN = tk.StringVar()
S_entry = tk.Entry(self.second,textvariable=self.SRN)
S_Button2 = tk.Button(self.second,text="Store in Database",command=self.data)
# Packing widgets
S_entry.pack()
S_Button2.pack()
def data(self):
self.second.destroy()
print(self.SRN.get())
if __name__ == "__main__":
root = tk.Tk()
app = Sample(root)
root.mainloop()
不要使用from tkinter import *,它不遵循PEP8。而是使用import tkinter as tk或類似。不要使用button = tk.Button().pack(). 將按鈕創建與包裝分開,這使得在有更多小部件時更容易正確訂購小部件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/362005.html
上一篇:在tkinter中列印串列的總和
