Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

python - tkinter button in class can't call function

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

What I'm trying to do SHOULD be simple:

  1. Make a button.
  2. Connect that button go a function.
  3. Click button --> run function.

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)...

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.

Here's the code:

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()

What am I doing wrong?

How to do it right?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...