从条目python3获取变量

2024-04-25 02:25:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: 函数textgetcolumnbuttonrootleftgrid
1条回答
网友
1楼 · 发布于 2024-04-25 02:25:57

保留对小部件的引用,然后使用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()

相关问题 更多 >