首页 > 解决方案 > 无法将命令绑定到按钮 Python 3.7

问题描述

我正在尝试获得一个按钮来在 Python 中做一些事情(使用 Tkinter)。我希望按钮获取组合框的当前选择并将其打印在屏幕上。

图形布局是 3 个独立的框架,但按钮和组合框都位于同一框架中(框架 #2)。

问题是我无法引用组合框。我正在阅读的错误:

Frame object has no attribute 'box'

Window object has no attribute 'box'

self.box=ttk.Combobox(self.frame2 , values[...])
self.button1=tk.Button(self.frame2, command= self.wipe(), text=...)

def wipe(self):
    self.box.get()

或者我试过:

def wipe(self):
    self.frame2.box.get()

目标是简单地从组合框中获取选定的选项。

这是产生相同错误的最小编码:

import tkinter as tk
from tkinter import ttk

class window():
    def __init__(self,root):
        self.frame=tk.Frame(root)
        self.key=tk.Button(self.frame,text='PRESS ME',command=self.wipe())
        self.box=ttk.Combobox(self.frame, options=['1','2','3'])
        self.frame.pack()
        self.key.pack()
        self.box.pack()
    def wipe(self):
        self.box.get()

master=tk.Tk()
master.geometry('400x400')
app=window(master)
master.mainloop()

标签: pythonpython-3.xbuttontkinter

解决方案


我会在问题中添加标签“tkinter”。

尝试以下操作:

def wipe(self):
    # code

self.box=ttk.Combobox(self.frame2 , values[...])
self.button1=tk.Button(self.frame2, command=wipe, text=...)

请注意以下事项:

  1. 我首先定义了擦除,然后才使用它。
  2. 我不太清楚你为什么要这样做command=self.wipe(),因为这里有两个问题。首先,您设置command的结果self.wipe()不是函数。第二,你没有定义self.wipe,你定义了wipe
  3. command=wipecommand关键字参数设置为函数wipe

自从我处理 tkinter 以来已经很久了,如果这不起作用,我将尝试通过再次检查文档来提供帮助。


推荐阅读