2012-05-07 47 views
0

所以我編寫了這個GUI程序(使用tkinter),並且我在同一個函數中使用了三個Entrybox。我想在主函數中使用它們的值,那麼如何將這些值轉換成某種全局變量或者我可以在不同的函數中使用它們?從條目PYTHON 3獲取變量

def options(): 

    options_root = Tk() 

    textFrame = Frame(options_root) 
    textFrame.grid() 

    widthlabel = Label(textFrame, text="w:", justify=LEFT) 
    widthlabel.grid(column="0", row="0") 
    widthinput = Entry(textFrame) 
    widthinput.grid(column="1", row="0") 

    heightlabel = Label(textFrame, text="h:", justify=LEFT) 
    heightlabel.grid(column="0", row="1") 
    heightinput = Entry(textFrame) 
    heightinput.grid(column="1", row="1") 

    mlabel = Label(textFrame, text="m:", justify=LEFT) 
    mlabel.grid(column="0", row="2") 
    minput = Entry(textFrame) 
    minput.grid(column="1", row="2") 

    width = widthinput.get() 
    height = heightinput.get() 
    m = minput.get() 


    start_game_button = Button(options_root, text="Start", justify=LEFT, command=lambda:tabort(options_root)) 
    start_game_button.grid(column="0",row="3") 
    exit_button = Button(options_root, text = "Exit", justify=LEFT, command=exit) 
    exit_button.grid(column="1", row="3") 

    mainloop() 

def main(): 

    options() 

    w = widthinput.get() 
    h = heightinput.get() 
    m = minput.get() 

main() 

回答

3

保留對小部件的引用,然後使用get()方法。如果您將應用程序設計爲一個類,這將變得更加容易:

import tkinter as tk 

class SampleApp(tk.Tk): 
    def __init__(self, ...): 
     ... 
     self.width_entry = tk.Entry(...) 
     self.height_entry = tk.Entry(...) 
     self.minput_entry = tk.Entry(...) 
     ... 
    def main(...): 
     w = self.width_entry.get() 
     h = self.height_entry.get() 
     m = self.input_entry.get() 
     ... 

... 
app = SampleApp() 
app.mainloop() 
+0

所以現在我得到了這個錯誤,並且在一個類中做了這個。 w = ins.width() TypeError:'int'對象不可調用 – tivon

+0

@tivon:etror消息的哪部分不明白?它告訴你到底是什麼錯誤。你似乎認爲'width'是一個函數,但python認爲它是一個int。 –