【问题标题】:How can I use .get() tkinter in another def? Python如何在另一个 def 中使用 .get() tkinter? Python
【发布时间】:2017-04-11 16:28:13
【问题描述】:

我的问题是我需要从输入框中获取信息,从另一个 def 作为整数。但是我总是遇到输入框中没有参数的问题,或者我无法将字符串转换为整数。

from tkinter import *
import os.path
import sys
import logging
#import mainloop
import main_draw_window
Size_Format="px"
def div_edit_window():
    edit_window = Tk()
    edit_window.title(main_draw_window._Projekt_Name+": DIV Editor")
    div_size_format_changer_bt = Button(edit_window, text="It is "+Size_Format, command=div_change)
    div_ending_x_ent = Entry(edit_window)
    div_ending_y_ent = Entry(edit_window)
    div_ending_accept = Button(edit_window, text="Accept", command=div_ending_set)
    div_size_format_changer_bt.pack()
    div_ending_x_ent.pack()
    div_ending_y_ent.pack()
    div_ending_accept.pack()
    edit_window.mainloop()

def div_ending_set():
    div_ending_x = int(div_edit_window.div_ending_x_ent.get())
    div_ending_y = int(div_edit_window.div_ending_y_ent.get())
    print(div_ending_x)
    print(div_ending_y)

感谢您的帮助;)

【问题讨论】:

  • div_edit_window() 是一个函数,您可能希望它是一个类。
  • 惰性解决方案:全局变量。很好的解决方案,但需要更广泛的重新设计:类。

标签: python function tkinter get


【解决方案1】:

问题在于我在 another answer of mine 中谈到过的 Python 作用域。

正如Kevin所说,你可以使用全局声明:

global foo

这是不鼓励的,global 的最佳用法根本不是global,所以我不会解释它是如何工作的。


实现这项工作的另一种方法是使用类。在类中,def 可以使用来自其他函数的定义,这正是您想要的。通常你不能在函数之间使用它们,例如,这会引发错误:

def foo1():
    string = 'x'
def foo2():
    print(string)

foo1() #You would expect this to define the string
foo2() #So this can print it... but no.

但这会起作用:

class foo:
    def foo1(self):
        self.string = 'x'
    def foo2(self):
        print(self.string)

MyClass = foo()

MyClass.foo1()
MyClass.foo2()

每行解释:

首先,这一行:

MyClass = foo()

这实际上是在制作所谓的类的实例。这将允许访问实例中定义的每个变量、函数或其他事物,来自:

  • 在同一个实例之外,甚至在类或任何类之外,通过使用MyClass.varMyClass.var()等。
  • 从实例中,通过使用self.varself.var()等。

这样想:A 是一个类的实例,它有一个方法foo() 和一个方法bar()。在代码中的某处foo() 调用bar()。如果您想在代码中的任何位置从A 调用foo() 函数,请使用:A.foo()。如果你有另一个实例,B 然后调用Bfoo() 你使用B.foo() 等等。当来自任何实例的foo() 从同一实例调用bar() 时,代码行是self.bar()。所以,self 代表一个类的任何实例。

其他行

  1. 这类似于定义一个函数,您是在告诉 Python 下一个缩进的行属于一个类(而不是一个函数)
  2. 定义一个不带参数的函数(self 在类中是必须的,there is a reason for this
  3. string = 'x' 这个类的每个实例
  4. 同 2。
  5. 在屏幕中显示对应的(带有实例的)字符串x

然后实例化类,并调用foo1()foo2()


现在您可以应用这些知识来修复您的代码。如果有什么不清楚的地方,我会编辑我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-16
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    相关资源
    最近更新 更多