[英]Not able to get Tkinter Values outside of class
我用 PAGE 構建器創建了一個簡單的 tKinter Gui,我可以單擊一個按鈕並在其中執行相應的命令 function。 但是,當我嘗試獲取 function 中特定文本框的值時,我遇到了各種錯誤,大部分是找不到此類屬性。 我嘗試將 self 和 class 名稱添加到屬性中,甚至從 class 傳遞屬性,並在 class 中使其成為 function,但我似乎仍然無法訪問文本框“用戶名”的值。 我真的很感激任何有關如何在 function 中獲取這些文本框值的幫助,因為我已經研究了幾個小時但仍然無法使其工作。 此外,如果有人知道關於此主題的任何好的教程,將會有很大幫助。 謝謝你。
該項目有 2 個文件:(我試圖刪除非必要的代碼)
MacUpdaterPageDesign.py
import sys
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *
import os.path
_script = sys.argv[0]
_location = os.path.dirname(_script)
import MacUpdaterPageDesign_support
class Toplevel1:
def __init__(self, top=None):
top.title("Mac Updater")
top.configure(background="#d9d9d9")
self.top = top
self.MainFrame = tk.Frame(self.top)
self.MainFrame.place(relx=0.0, rely=0.18, relheight=0.811
, relwidth=1.099)
self.Username = tk.Text(self.MainFrame)
self.Username.place(relx=0.15, rely=0.081, relheight=0.048
, relwidth=0.279)
#this button calls the CopyMACfunc on the support page
self.CopyMAC = tk.Button(self.MainFrame)
self.CopyMAC.place(relx=0.143, rely=0.846, height=34, width=117)
self.CopyMAC.configure(command=MacUpdaterPageDesign_support.CopyMACfunc)
self.CopyMAC.configure(text='Copy MAC')
MacUpdaterPageDesign_support.py
import sys
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.constants import *
import MacUpdaterPageDesign
def main(*args):
'''Main entry point for the application.'''
global root
root = tk.Tk()
root.protocol( 'WM_DELETE_WINDOW' , root.destroy)
# Creates a toplevel widget.
global _top1, _w1
_top1 = root
_w1 = MacUpdaterPageDesign.Toplevel1(_top1)
root.mainloop()
def CopyMACfunc(*args):
#this part must retrieve the value in from Username
#tried many variations of below but throws error
username = MacUpdaterPageDesign.Username.get("1.0",END)
print(username)
if __name__ == '__main__':
MacUpdaterPageDesign.start_up()
實際上,在寫這個問題時,我終於讓它起作用了:
username = _w1.Username.get("1.0",END)
它確實適用於以下但不確定這是否是正確的方法。 如果有人知道,也許他們是更好的方法。 也將不勝感激任何有關好的教程或在哪里可以學習所有此類信息的建議。 謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.