【问题标题】:Tkinter calling functions within classes类中的 Tkinter 调用函数
【发布时间】:2016-03-03 15:41:02
【问题描述】:

在我的新程序中,我一直显示相同的代码行,所以我决定创建一个函数,并在需要时调用它。但我不断收到一个错误消息,告诉我“我的功能未定义”。我是 Python 编程的新手,我想不通!

这是我的代码:

import tkinter as tk
from tkinter import ttk

class GUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        #Window_Creation
        scr_xloc = int(self.winfo_screenwidth() / 2 - 800 / 2)
        scr_yloc = int(self.winfo_screenheight() / 2 - 600 / 2 - 30)

        self.geometry("800x600+{}+{}".format(scr_xloc, scr_yloc))
        self.minsize(width = 800, height = 600)
        ...

    def Factorial_Calculation():
        user_input = int(float(user_input))
        import math

        factorial_num = math.factorial(user_input)

        self.Output_Box.delete("1.0", "end")
        self.Output_Box.insert("1.0", str(user_input) + "! = " + str(factorial_num))

    def x_Factorial_Loop(self, event):
        global user_input
        ...

        Factorial_Calculation()

【问题讨论】:

  • 您的缩进可能已关闭。您是否同时使用制表符和空格?
  • 您得到的准确且完整的错误信息是什么?
  • NameError: 名称“Factorial_Calculation”未定义

标签: function class python-3.x tkinter


【解决方案1】:

你的问题是调用Factorial_Calculation(),你应该在类内调用它为self.Factorial_Calculation(),但类外是另一回事。在您调用的函数前添加“self.”,因为它适用于您调用它的类并从您调用它的类中提取定义。

【讨论】:

  • 是否需要在括号内放一个“自我”? def Factorial_Calculation(self):
  • 没错,但只是为了定义,否则调用的时候,照常做Factorial_Calculation()
猜你喜欢
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多