【问题标题】:Radiobutton selection in new window在新窗口中选择单选按钮
【发布时间】:2016-05-01 11:17:28
【问题描述】:

所以我正在使用 tkinter 制作电影推荐 GUI。当用户选择一个单选按钮时,我希望它在新窗口中打开,其中包含选择。因此,如果有人选择喜剧,我可以在不同的电影中编码,并让它们在新窗口中随机弹出。我有打开窗口的命令,但我无法回调选定的选项。

from tkinter import *

class movie1:
def __init__(self, master):
    self.master = master
    master.title("Movie Recommendation")

    self.label = Label(master, text= "Welcome to the movie recommendation application! \n Please select the genre of the movie you would like to see.")
    self.label.pack(padx=25, pady=25)

    CheckVar1 = StringVar()

    self.radiobutton = Radiobutton(master, text = "Action", variable=CheckVar1, value=1, command=self.reco)
    self.radiobutton.pack(side=TOP, padx=10, pady=10)

    self.radiobutton = Radiobutton(master, text = "Comedy", variable=CheckVar1, value=2, command=self.reco)
    self.radiobutton.pack(side=TOP, padx=10, pady=10)

    self.radiobutton = Radiobutton(master, text = "Documentary", variable=CheckVar1, value=3, command=self.reco)
    self.radiobutton.pack(side=TOP, padx=10, pady=10)

    self.radiobutton = Radiobutton(master, text = "Horror", variable=CheckVar1, value=4, command=self.reco)
    self.radiobutton.pack(side=TOP, padx=10, pady=10)

    self.radiobutton = Radiobutton(master, text = "Romance", variable=CheckVar1, value=5, command=self.reco)
    self.radiobutton.pack(side=TOP, padx=10, pady=10)

    self.radiobutton.cget("value")


def reco(self):
    self.newWindow = Toplevel(self.master)
    if ("value") == 1:
        print("1")


root = Tk()
my_gui = movie1(root)
root.mainloop()

【问题讨论】:

标签: python user-interface tkinter


【解决方案1】:

也许这对你有帮助。

首先:将第 11 行更改为:self.CheckVar1 = IntVar(),因为radiobutton 中的答案值是整数,而不是字符串。此外,我们将self. 添加到CheckVar1 变量中,因为我们希望稍后在reco 方法中访问它。

第二:将第 33 行更改为:if self.CheckVar1.get() == 1:。这里我们使用了与变量self.CheckVar1相关联的.get()方法来获取其中存储的值。

现在,如果您运行脚本,当您选择 Action 选项时,您将打印出 "1"(在 IDLE 中)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-08
    • 2017-06-02
    • 2017-09-28
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    相关资源
    最近更新 更多