简体   繁体   English

如何在Python中使用类(类在我的代码中不起作用)

[英]How to use classes in Python (Classes are not working in my code)

I made a code then decided to split it up into a GUI class and a logic class but now that I have done that the code does not function after I made the two classes, it works without the classes but I am trying to make it work with classes. 我编写了一个代码,然后决定将其拆分为一个GUI类和一个逻辑类,但是现在我已经做到了在创建两个类之后该代码不起作用,它在没有这些类的情况下也可以工作,但是我试图使其工作与类。 if someone could fix this problem I will be so grateful. 如果有人可以解决此问题,我将非常感激。 Any help will be kindly appreciated thank you. 任何帮助将不胜感激,谢谢。

from tkinter import *
import tkinter as tk
from tkinter import ttk

class GUI:
    notebook = ttk.Notebook(root)
    frame1 = ttk.Frame(notebook)
    notebook.add(frame1, text='Length')
    frame2 = ttk.Frame(notebook)
    notebook.add(frame2, text='Weight')
    frame3 = ttk.Frame(notebook)
    notebook.add(frame3, text='Temperature')
    notebook.pack(expand=1, fill="both")
    #======================================================================
    entry = Entry(frame1)
    entry.grid(row=0, column=0)

    label = Label(frame1, relief='groove', width=20, text='')
    label.grid(row=0, column=3)

    options1 = ['mm', 'cm', 'm', 'km', 'Inches', 'Feet', 'Yards', 'Miles']

    var1 = tk.StringVar(frame1)
    var1.set(options1[0])

    dropdown1 = tk.OptionMenu(frame1, var1, options1[0], options1[1], options1[2], options1[3], options1[4], options1[5], options1[6], options1[7])
    dropdown1.grid(row=1, column=0)

    var2 = tk.StringVar(frame1)
    var2.set(options1[0])

    dropdown2 = tk.OptionMenu(frame1, var2, options1[0], options1[1], options1[2], options1[3], options1[4], options1[5], options1[6], options1[7])
    dropdown2.grid(row=1, column=3)

    equal_button = Button(frame1, text='=', command=Length_Error) 
    equal_button.grid(row=1, column=5)
    #======================================================================
    weight_entry = Entry(frame2)
    weight_entry.grid(row=0, column=0)

    weight_label = Label(frame2, relief='groove', width=20, text='')
    weight_label.grid(row=0, column=3)

    options2 = ['Grams', 'Kilograms', 'Ounces', 'Pounds', 'Tonnes']

    weight_var1 = tk.StringVar(frame2)
    weight_var1.set(options2[0])

    dropdown1 = tk.OptionMenu(frame2, weight_var1, options2[0], options2[1], options2[2], options2[3], options2[4])
    dropdown1.grid(row=1, column=0)

    weight_var2 = tk.StringVar(frame1)
    weight_var2.set(options2[0])

    dropdown2 = tk.OptionMenu(frame2, weight_var2, options2[0], options2[1], options2[2], options2[3], options2[4])
    dropdown2.grid(row=1, column=3)

    weight_equal_button = Button(frame2, text='=', command=Weight_Error) 
    weight_equal_button.grid(row=1, column=5)
    #======================================================================
    temp_entry = Entry(frame3)
    temp_entry.grid(row=0, column=0)

    temp_label = Label(frame3, relief='groove', width=20, text='')
    temp_label.grid(row=0, column=3)

    options3 = ['Celsius', 'Fahrenheit', 'Kelvin']

    temp_var1 = tk.StringVar(frame3)
    temp_var1.set(options3[0])

    temp_dropdown1 = tk.OptionMenu(frame3, temp_var1, options3[0], options3[1], options3[2])
    temp_dropdown1.grid(row=1, column=0)

    temp_var2 = tk.StringVar(frame3)
    temp_var2.set(options3[0])

    temp_dropdown2 = tk.OptionMenu(frame3, temp_var2, options3[0], options3[1], options3[2])
    temp_dropdown2.grid(row=1, column=3)

    temp_equal_button = Button(frame3, text='=', command=Temperature_Error) 
    temp_equal_button.grid(row=1, column=5)
    #======================================================================

class logic:
    #======================================================================
    def Length_Error(*args):
        try:
            v = float(entry.get())       
        except ValueError:
            label['text']=('Enter Valid Input')
        else:
            Length_converter()
    #======================================================================
    def Weight_Error(*args):
        try:
            v = float(weight_entry.get())
        except ValueError:
            weight_label['text']=('Enter Valid Input')
        else:
            Weight_converter()
    #======================================================================
    def Temperature_Error(*args):
        try:
            v = float(temp_entry.get())
        except ValueError:
            temp_label['text']=('Enter Valid Input')
        else:
            Temperature_converter()
    #======================================================================
    def Length_converter(*args):
        v = float(entry.get())
        metre_dict = dict(mm= 0.001, cm= 0.01, m= 1, km= 1000, Inches= 0.0254, Feet= 0.3048, Yards= 0.9144, Miles= 1609.344)
        M = v * metre_dict[var1.get()]
        k = M / metre_dict[var2.get()]
        label['text']=k
    #======================================================================
    def Weight_converter(*args):
        v = float(weight_entry.get())
        weight_dict = dict(Grams= 1, Kilograms= 1000, Ounces= 28.34952313, Pounds= 453.59237, Tonnes= 1000000)
        M = v * weight_dict[weight_var1.get()]
        k = M / weight_dict[weight_var2.get()]
        weight_label['text']=k
    #======================================================================
    def Temperature_converter(*args):
        temp_dict = dict(Fahrenheit=(1/1.8, -32/1.8), Celsius=(1, 0), Kelvin=(1, -273.15))
        x, y= temp_dict[temp_var1.get()]
        cels = float(temp_entry.get()) * x + y
        x, y = temp_dict[temp_var2.get()]
        answer = (cels - y) / x
        temp_label['text']=answer

        root.mainloop

If you create class for logic then it should get arguments and return result and not use widgets. 如果为逻辑创建类,则它应该获取参数并返回结果,而不使用小部件。 Button should run function which get values from widgets and use them with Logic, and latere get result and put to widget. Button应该运行从小部件获取值并将其与Logic一起使用的函数,然后再获取结果并放入小部件。

This class Logic doesn't have to remeber values so I think method can be static. 此类Logic不必记住值,因此我认为方法可以是静态的。

In class we put code rateher in methods and we use self. 在课堂上,我们将代码评级器放入方法中,然后使用self. to have access to the same variables in different methods in class 在类中的不同方法中可以访问相同的变量

#### from tkinter import *  <-- not preferred

import tkinter as tk
from tkinter import ttk

class GUI:

    def __init__(self):  # <-- init class

        root = tk.Tk()  # <-- main window

        notebook = ttk.Notebook(root)
        frame1 = ttk.Frame(notebook)

        notebook.add(frame1, text='Length')
        frame2 = ttk.Frame(notebook)

        notebook.add(frame2, text='Weight')
        frame3 = ttk.Frame(notebook)

        notebook.add(frame3, text='Temperature')
        notebook.pack(expand=1, fill="both")

        #======================================================================

        self.entry = tk.Entry(frame1)  # <-- self. / tk.
        self.entry.grid(row=0, column=0)  # <-- self.

        self.label = tk.Label(frame1, relief='groove', width=20, text='')  # <-- self. / tk.
        self.label.grid(row=0, column=3)  # <-- self.

        options1 = ['mm', 'cm', 'm', 'km', 'Inches', 'Feet', 'Yards', 'Miles']

        self.var1 = tk.StringVar(frame1)  # <-- self.
        self.var1.set(options1[0])  # <-- self.

        dropdown1 = tk.OptionMenu(frame1, self.var1, *options1)  # <-- self. / *options1
        dropdown1.grid(row=1, column=0)

        self.var2 = tk.StringVar(frame1)  # <-- self.
        self.var2.set(options1[0])  # <-- self.

        dropdown2 = tk.OptionMenu(frame1, self.var2, *options1)  # <-- self. / *options1
        dropdown2.grid(row=1, column=3)

        equal_button = tk.Button(frame1, text='=', command=self.convert_length)   # <-- tk. / function in GUI
        equal_button.grid(row=1, column=5)

        #======================================================================

        self.weight_entry = tk.Entry(frame2)  # <-- self. / tk.
        self.weight_entry.grid(row=0, column=0)  # <-- self.

        self.weight_label = tk.Label(frame2, relief='groove', width=20, text='')  # <-- self. / tk.
        self.weight_label.grid(row=0, column=3)  # <-- self.

        options2 = ['Grams', 'Kilograms', 'Ounces', 'Pounds', 'Tonnes']

        self.weight_var1 = tk.StringVar(frame2)  # <-- self.
        self.weight_var1.set(options2[0])  # <-- self.

        dropdown1 = tk.OptionMenu(frame2, self.weight_var1, *options2)  # <-- self. / *options2
        dropdown1.grid(row=1, column=0)

        self.weight_var2 = tk.StringVar(frame1)  # <-- self.
        self.weight_var2.set(options2[0])  # <-- self.

        dropdown2 = tk.OptionMenu(frame2, self.weight_var2, *options2)  # <-- self. / *options2
        dropdown2.grid(row=1, column=3)

        weight_equal_button = tk.Button(frame2, text='=', command=self.convert_weight)  # <-- tk. / function in GUI
        weight_equal_button.grid(row=1, column=5)

        #======================================================================

        self.temp_entry = tk.Entry(frame3)  # <-- self. / tk.
        self.temp_entry.grid(row=0, column=0)  # <-- self.

        self.temp_label = tk.Label(frame3, relief='groove', width=20, text='')  # <-- self. / tk.
        self.temp_label.grid(row=0, column=3)  # <-- self.

        options3 = ['Celsius', 'Fahrenheit', 'Kelvin']

        self.temp_var1 = tk.StringVar(frame3)  # <-- self.
        self.temp_var1.set(options3[0])  # <-- self.

        temp_dropdown1 = tk.OptionMenu(frame3, self.temp_var1, *options3)  # <-- self. / *options3
        temp_dropdown1.grid(row=1, column=0)

        self.temp_var2 = tk.StringVar(frame3)  # <-- self.
        self.temp_var2.set(options3[0])  # <-- self.

        temp_dropdown2 = tk.OptionMenu(frame3, self.temp_var2, *options3)  # <-- self. / *options3
        temp_dropdown2.grid(row=1, column=3)

        temp_equal_button = tk.Button(frame3, text='=', command=self.convert_temp)   # <-- tk. / function in GUI
        temp_equal_button.grid(row=1, column=5)

        #======================================================================

        root.mainloop()  # <--- () , it starts window

    # <-- functions assigned to buttons

    def convert_length(self):
        var1 = self.var1.get()
        var2 = self.var2.get()

        try:
            value = float(self.entry.get())       
        except ValueError:
            self.label['text'] = 'Enter Valid Input'
            return

        try:
            self.label['text'] = Converter.convert_length(value, var1, var2)
        except Exception as ex:
            self.label['text'] = 'Exception: {}'.format(ex)

    def convert_weight(self):
        var1 = self.weight_var1.get()
        var2 = self.weight_var2.get()

        try:
            value = float(self.weight_entry.get())       
        except ValueError:
            self.weight_label['text'] = 'Enter Valid Input'
            return

        try:
            self.weight_label['text'] = Converter.convert_weight(value, var1, var2)
        except Exception as ex:
            self.weight_label['text'] = 'Exception: {}'.format(ex)

    def convert_temp(self):
        var1 = self.temp_var1.get()
        var2 = self.temp_var2.get()

        try:
            value = float(self.temp_entry.get())       
        except ValueError:
            self.temp_label['text'] = 'Enter Valid Input'
            return

        try:
            self.temp_label['text'] = Converter.convert_temperature(value, var1, var2)
        except Exception as ex:
            self.temp_label['text'] = 'Exception: {}'.format(ex)


class Converter: # <-- UpperCaseName

    @staticmethod
    def convert_length(v, var1, var2):  # <-- lower_case_name / arguments

        metre_dict = dict(mm= 0.001, cm= 0.01, m= 1, km= 1000, Inches= 0.0254, Feet= 0.3048, Yards= 0.9144, Miles= 1609.344)

        M = v * metre_dict[var1]
        k = M / metre_dict[var2]

        return k

    #======================================================================

    @staticmethod
    def convert_weight(v, var1, var2):  # <-- lower_case_name / arguments

        weight_dict = dict(Grams= 1, Kilograms= 1000, Ounces= 28.34952313, Pounds= 453.59237, Tonnes= 1000000)

        M = v * weight_dict[var1]
        k = M / weight_dict[var2]

        return k

    #======================================================================

    @staticmethod
    def convert_temperature(v, var1, var2):  # <-- lower_case_name / arguments

        temp_dict = dict(Fahrenheit=(1/1.8, -32/1.8), Celsius=(1, 0), Kelvin=(1, -273.15))

        x, y= temp_dict[var1]
        cels = v * x + y
        x, y = temp_dict[var2]

        return (cels - y) / x

# --- main ----

if __name__ == '__main__':
    GUI()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM