【问题标题】:Can't tie command to button Python 3.7 [duplicate]无法将命令绑定到按钮 Python 3.7 [重复]
【发布时间】:2019-04-23 16:09:41
【问题描述】:

我正在尝试获取一个按钮来在 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()

【问题讨论】:

标签: python python-3.x button tkinter


【解决方案1】:

我会在问题中添加标签“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 打交道了,如果这不起作用,我会尝试通过再次检查文档来提供帮助。

【讨论】:

  • 是的,我确实尝试在小部件之前定义函数,但它没有改变任何东西。我还尝试以各种其他方式来表达命令,但也没有太大变化(我的意思是 'command=self.wipe()' 、 'self.wipe' 等)
  • 请编辑您的问题以包含您的尝试。
猜你喜欢
  • 2013-09-16
  • 2011-03-18
  • 1970-01-01
  • 2012-02-26
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 2014-05-13
  • 2015-10-26
相关资源
最近更新 更多