2017-05-29 46 views
1

我試圖獲取輸入到在類中設置的tkinter Entry窗口小部件的值。我可以使用attribute.get()來檢索小部件不在類中時的值,但我不確定如何在類中調用它。Python - 從單獨的類中的tk輸入框中檢索值

我收到的錯誤是:

File "C:/Users/ABour/Python Scripts/test/PassVarSX.py", line 12, in Enter_Inputs 
    xf_In = int(self.e_xf.get()) 
AttributeError: 'StartPage' object has no attribute 'e_xf' 

包含插件的類被稱爲StartPage和小部件被稱爲e_xf,使用.get()函數被調用Enter_Inputs

預先感謝您的幫助,我在Spyder上運行,Python v3.6

import tkinter as tk 
from tkinter import ttk 

LARGE_FONT= ("Verdana", 12) 

def To_Print(self): 
    xf = Enter_Inputs(self,'xf') 
    print('xf = ', xf) 

def Enter_Inputs(self,x): # Enter inputs from values typed in 

     xf_In = int(self.e_xf.get()) 

     if x == 'xf': 
      x = float(xf_In)/100 

     return x 


class TestApp(tk.Tk): 

    def __init__(self, *args, **kwargs): 

     tk.Tk.__init__(self, *args, **kwargs) 

     container = tk.Frame(self) 
     container.pack(side="top", fill="both", expand = True) 
     container.grid_rowconfigure(0, weight=1) 
     container.grid_columnconfigure(0, weight=1) 

     self.frames = {} 

     frame = StartPage(container, self) 

     self.frames[StartPage] = frame 

     frame.grid(row=0, column=0, sticky="nsew") 

     self.show_frame(StartPage) 

    def show_frame(self, cont): 

     frame = self.frames[cont] 
     frame.tkraise() 


class StartPage(tk.Frame): 

    def __init__(self, parent, controller): 
     tk.Frame.__init__(self,parent) 


     label = ttk.Label(self, text="Start Page", font=LARGE_FONT) 
     label.grid(row=0, columnspan = 2) 


     l_xf = tk.Label(self, text="% xA of Feed") 
     l_xf.grid(row=1) 

     e_xf = tk.Entry(self) 
     e_xf.grid(row=1, column=1) 


     b_run = tk.Button(self, text="Click to Run", command=lambda: To_Print(self)) 
     b_run.grid(row=2, column=0, columnspan = 2) 


app = TestApp() 
app.mainloop() 

回答

0

當你p屁股自我To_Print方法,你想從自己調用e_xf字段,你應該聲明e_xf作爲類的數據成員。

您可以通過簡單地改變行

self.e_xf = tk.Entry(self) 
self.e_xf.grid(row=1, column=1) 

通過該e_xf是一個實例成員做到這一點,你應該能夠從Enter_Inputs函數調用它。

+0

謝謝,完美的作品! –

+0

請問[接受答案](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)是否解決了你的問題:) –

相關問題