gpt4 book ai didi

python - 如何在另一个 def 中使用 .get() tkinter? Python

转载 作者:太空宇宙 更新时间:2023-11-03 15:23:14 24 4
gpt4 key购买 nike

我的问题是我需要从输入框中获取信息,从另一个 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)

感谢您的帮助;)

最佳答案

问题出在 Python 的作用域上,我在 another answer of mine 中讨论过它们。 .

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

<小时/>

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

关于python - 如何在另一个 def 中使用 .get() tkinter? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43351486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com