【问题标题】:Tkinter Radio Button Controlling If TrueTkinter 单选按钮控制是否为真
【发布时间】:2019-10-09 16:58:58
【问题描述】:

我正在尝试做一个简单的程序。我正在尝试检查单选按钮 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()

【问题讨论】:

  • bworking 当前是 first() 中的局部变量,并在该函数退出时消失。 second() 不可能访问它们。
  • 那我需要做什么?
  • 提示:为什么bati.filenameaskfile 内部工作?您处理bati 的方式与处理b 的方式有什么不同?具体来说:代码在哪里 bati 得到它的初始值?是在函数内部还是外部?

标签: python python-3.x tkinter tk


【解决方案1】:

问题:

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

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

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

  • Event handlers 应该接收event 参数,即使您忽略它。您在second 命令中编写的.widget 可能是从其他一些代码复制而来,这些代码试图找出要隐藏在事件数据中的小部件(例如here)。但是 .widget 将是发送命令的那个,即 Radiobutton,而不是您要隐藏的 Button。

我们要做的是提前在全局变量中创建按钮(在更严肃的项目中,您应该考虑使用类代替,然后使用类成员来记住它)。由于按钮一开始应该是不可见的,我们只是不立即使用.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()

【讨论】:

  • 感谢您的帮助p :)))
猜你喜欢
  • 2019-09-04
  • 2018-02-06
  • 1970-01-01
  • 2014-05-05
  • 2016-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多