类中的 tkinter 按钮无法调用函数 [英] tkinter button in class can't call function

查看:29
本文介绍了类中的 tkinter 按钮无法调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完全的菜鸟,认真而愤怒地与 Python 斗争......

Total noob, seriously and angrily struggling with Python...

我想要做的应该很简单:

What I'm trying to do SHOULD be simple:

  1. 制作一个按钮.
  2. 连接那个按钮去一个功能.
  3. 点击按钮 --> 运行函数.

当我们必须使用 CLASS 时,问题就来了(无论我阅读、学习多少,甚至付钱上课,对我来说都是零意义的)...

The problem comes when we have to use CLASS (which, no matter how much I read, study - or even pay to take classes continues to make zero sense to me)...

我已经尝试了将这个小的 convert() 函数放入类中的所有可能的组合,添加 self.convert 或 root.convert - 但没有一个有效.而且,我不知道为什么 - 或者接下来要尝试什么.

I've tried every concieveable combination of putting this little convert() function IN the class, of adding self.convert or root.convert - and NONE of it works. And, I am clueless why - or what to try next.

代码如下:

from tkinter import *
from tkinter.ttk import Frame, Button, Style


def convert():
    print("clicked")
    kg = entry_kg.get()
    print(kg)



class Example(Frame):

    def __init__(self):
        super().__init__()

    self.initUI()    # initiate the GUI
    # -------------------------------


    def initUI(self):

        self.master.title("Weight Converter")
        self.pack(fill=BOTH, expand=True)
        # -------------------------------------

        frame_kg = Frame(self)   # frame for Kilograms
        frame_kg.pack(fill=X)

        lbl_kg = Label(frame_kg, text="Kilograms", width=16)
        lbl_kg.pack(side=LEFT, padx=5, pady=5)

        entry_kg = Entry(frame_kg)
        entry_kg.pack(fill=X, padx=(5, 30), expand=True)
        # ------------------------------------------------

        frame_btn = Frame(self)    # frame for buttons
        frame_btn.pack(fill=BOTH, expand=True, padx=20, pady=5)

        btn_convert=Button(frame_btn, text="Convert", command=convert)
        btn_convert.pack(side=LEFT, padx=5, pady=5)

        # -------------------------------------------

def main():

    root = Tk()
    root.geometry("300x200+300+200")
    app = Example()
    root.mainloop()


if __name__ == '__main__':
    main()

我做错了什么?

如何做对?

看似随意且无用的简单任务的过度复杂化令人发狂......

The seemingly arbitrary and useless over-complication of a simple task is seriously maddening...

推荐答案

如果你想在类之外设计你的函数,但想从类中定义的按钮调用它,解决方案是创建一个方法在您的类中,它接受输入值,然后将它们传递给外部函数.

If you want your functions to be designed outside of the class, but want to call it from a button defined in the class, the solution is to create a method in your class which takes the input values and then passes them to the external function.

这称为解耦.您的功能与 UI 的实现解耦,这意味着您可以在不更改功能的情况下完全更改 UI 的实现,反之亦然.这也意味着您可以在许多不同的程序中重用相同的函数而无需修改.

This is called decoupling. Your function is decoupled from the implementation of the UI, and it means that you are free to completely change the implementation of the UI without changing the function, and vice versa. It also means that you can reuse the same function in many different programs without modification.

您的代码的整体结构应如下所示:

The overall structure of your code should look something like this:

# this is the external function, which could be in the same
# file or imported from some other module
def convert(kg):
    pounds = kg * 2.2046
    return pounds

class Example(...):
    def initUI(self):
        ...
        self.entry_kg = Entry(...)
        btn_convert=Button(..., command=self.do_convert)
        ...

    def do_convert(self):
        kg = float(self.entry_kg.get())
        result = convert(kg)
        print("%d kg = %d lb" % (kg, result))

这篇关于类中的 tkinter 按钮无法调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆