0

所以我正在编写这个 GUI 程序(使用 tkinter)并且我在同一个函数中使用了三个 Entryboxes。我想在主函数中使用它们的值,那么如何将这些值放入某种全局变量中,或者以一种可以在不同函数中使用它们的方式?

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

1 回答 1

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()
于 2012-05-07T11:04:05.863 回答