Tkinter packge for python,如何返回所选选项?

2024-09-29 22:12:39 发布

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

我正在学习tkinter,并希望在我的项目中使用它,但我一直在思考如何做到这一点。我想知道代码如何返回所选选项

代码如下:

from tkinter import *
from tkinter.ttk import *

master = Tk()
master.geometry("175x200")

v = StringVar(master, "1")

options = {
          "RadioButton 1": "1",
          "RadioButton 2": "2",
          "RadioButton 3": "3",
          "RadioButton 4": "4",
          "RadioButton 5": "5"
}

for (text, value) in options.items():
    Radiobutton(master, text=text, variable=v,
                value=value).pack(side=TOP, ipady=5)

print(StringVar())

quit_btn = Button(master, text="Quit", command=master.quit, width=10)
quit_btn.pack()

mainloop()

def selected_opition():
    return options.get(text, value)

print(selected_opition())

Tags: 代码textfromimportmastervaluetkinterpack
1条回答
网友
1楼 · 发布于 2024-09-29 22:12:39

虽然还有一些小错误,但要点是只在按下按钮后调用v.get()。所以你必须把它放在一个函数中,就像我用quitbutton()函数做的那样。该函数将在单击按钮时立即调用,因为它显示command=quitbutton

另外,您尝试打印StringVar(),但不应该这样做。您创建了一个变量v,它是StringVar。之后,您应该调用该v而不是StringVar。因此,与其做print(StringVar),不如做print(v.get())

我还建议您在Youtube上观看一些关于Tkinter的教程,因为这将增强您对基本原理的理解。您的代码非常好,但它缺少一些基础知识,这使得它无法按您希望的方式工作

from tkinter import *
from tkinter.ttk import *

master = Tk()
master.geometry("175x200")

# Changed this do StringVar() without anything in it and set the beginning value to 1
v = StringVar(master)
v.set(1)

options = {
          "RadioButton 1": "1",
          "RadioButton 2": "2",
          "RadioButton 3": "3",
          "RadioButton 4": "4",
          "RadioButton 5": "5"
}

for (text, value) in options.items():
    Radiobutton(master, text=text, variable=v,
                value=value).pack(side=TOP, ipady=5)

# Created a function that runs every time the button gets clicked (see the command=quitbutton in the Button widget) and gets the value of the button that is selected
def quitbutton():
    print(v.get())
    # master.quit() uncomment this line if you want to close the window after clicking the button


# Changed the function which gets called by changing the word after command=
quit_btn = Button(master, text="Quit", command=quitbutton, width=10)
quit_btn.pack()

mainloop()

相关问题 更多 >

    热门问题