Tkinter 单选按钮控制是否为真

Tkinter Radio Button Controlling If True

我正在尝试做一个简单的程序。我正在尝试检查单选按钮 1 是否被选中显示一个按钮,单选按钮 2 是否被选中以及屏幕上是否有一个按钮将其消失。请帮助我。

from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
bati = tkinter.Tk()
bati.geometry('500x500')
bati.title('Project')
def hello():
    messagebox.showinfo("Say Hello", "Hello World")

def askfile():
    bati.filename =  filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
    lb2 = Label(bati, text=bati.filename, fg='red', font=("Times", 10, "bold"))
    lb2.place(x='270',y='34')


def first():
    b = Button(bati, text='Import', activebackground='red', bd='3', bg='gray', fg='yellow', font=("Times New Roman", 10, "bold"), command=askfile)
    b.place(x='200',y='30')
    working = True

def second():
    if working == True:
        b.widget.pack_forget()
        working = False

canvas_width = 3000
canvas_height = 220
w = Canvas(bati, width=canvas_width,height=canvas_height)
w.pack()


y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y, fill="#476042", width='2')

v = IntVar()
v.set('L')

rb1 = Radiobutton(bati, text='Import A File', value=1, variable=v, command=first, font=("Comic Sans MS", 10, "bold"))
rb2 = Radiobutton(bati, text='Choose From Web', value=2, variable=v, command=second, font=("Comic Sans MS", 10, "bold"))
rb1.place(x='50',y='30')
rb2.place(x='50',y='50')
working = False


bati.mainloop()

问题:

  • 局部变量对此不起作用 - 您需要记住 firstsecond 之外的按钮状态,以便下次使用它。

  • 我们用.place显示按钮,所以我们应该用.place_forget而不是.pack_forget隐藏它。

  • .place位置应该用整数而不是字符串给出。同样对于按钮的 bd,即边框宽度(以像素为单位,即 像素)。

  • Event handlers are supposed to receive an event parameter, even if you ignore it. The .widget you've written in your second command is presumably copied from some other code that tries to find out the widget to hide from the event data (e.g. here)。但是 .widget 将是发送命令的那个,即单选按钮,而不是您要隐藏的按钮。

我们要做的是提前在全局变量中创建按钮(在更严肃的项目中,您应该考虑使用 classes,然后您将使用 class 会员记住)。由于按钮一开始应该不可见,我们只是不立即 .place 它,而是在 first 中使用 .place 并在 second 中使用 .place_forget。所以:

b = Button(
    bati, text='Import', activebackground='red', bd=3,
    bg='gray', fg='yellow', font=("Times New Roman", 10, "bold"),
    command=askfile
)

def first(event):
    b.place(x=200,y=30)

def second():
    b.place_forget()