关于python:在tkinter中声明全局并导入模块 | 珊瑚贝

declaration of global in tkinter with import of module

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from tkinter import *
from tkinter import ttk
import calculation_feet_metres
from calculation_feet_metres import *

root = Tk()
root.title(“Feet to Metres”)

”’
def calculate(*args):
    try:

        value = float(feet.get())
        metres.set((0.3048 * value * 10000.0 + 0.5)/10000.0)
    except ValueError:
        pass
”’

mainframe = ttk.Frame(root, padding=“3 3 12 12”)
mainframe.grid(column=0, row=0, sticky=(N,W,E,S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0,weight=1)
feet =StringVar()
metres = StringVar()

feet_entry = ttk.Entry(mainframe, width = 7, textvariable = feet)
feet_entry.grid(column=2, row=1, sticky=(W,E))

ttk.Label(mainframe, textvariable = metres).grid(column=2, row=2, sticky=(W,E))
ttk.Button(mainframe, text=“Calculate”, command = calculate).grid(column=3, row=3, sticky=W)

ttk.Label(mainframe, text =‘feet’).grid(column=3, row=1, sticky=W)
ttk.Label(mainframe, text =‘is equivalent to’).grid(column=1, row=2, sticky=E)
ttk.Label(mainframe, text =‘metres’).grid(column=3, row=2, sticky=W)

for child in mainframe.winfo_children():
   child.grid_configure(padx=5, pady=5)

feet_entry.focus()
root.bind(‘<Return>’, calculate)

root.mainloop()


以上返回

1
2
    value = float(feet.get())
NameError: global name ‘feet’ is not defined.

如果我”激活”函数 def calculate(*arg) 并注释掉 import calculation_feet_metres,转换器就可以工作(从 Modern Tkinter 复制)。

我试图了解如何导入一个模块(在这种情况下,我还有一个包含相同 def calculate(*arg) 脚本的模块,称为 calculation_feet_metres)并从该模块调用一个函数。我不明白在哪里定义,也不知道如何在这种情况下定义 global.


从不同模块导入的函数在它们被导入的模块中看不到全局变量。

全局变量对于定义函数的模块是”本地的”。

你可以将你的函数package在一个 lambda 中:

1
ttk.Button(mainframe, text=“Calculate”, command = lambda: calculate(feet)).grid(column=3, row=3, sticky=W)

并更改您的 calculate 函数以接受 feet 作为显式参数:

1
def calculate(feet):
  • 有了这个,我得到一个错误,我正在向 lambda 提供 0 个参数。我担心我对此很陌生,所以我真的不明白我只是在复制你写的东西,所以也许你假设了一些我应该知道的东西???使这项工作
  • @user1478335:对不起,我的错误,按钮 command 参数不带任何参数。我删除了 a 参数。


来源:https://www.codenong.com/14295392/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9453.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?