![](/img/trans.png)
[英]In Python, how can I use a function's return statement within a second function without using global variables?
[英]Python, Tkinter: Can a list be modified within a button callback without using global variables or defining new classes?
理想情況下,我想使用像tk.StringVar
這樣的內置方法來修改按鈕命令中的(字符串)列表,但還需要修改后的列表繼續存在,以便可以在額外的 function 調用中對其進行修改。 下面代碼中的print(a)
行打印了一個類似列表的 object ('abc', 'gh', 'rstu')
,但是print(a[1])
行無法返回gh
並且a.append('xyz')
行a.append('xyz')
返回一個錯誤(包括在下面),表明我不能直接劫持tk.StringVar
來攜帶列表。 如果我應該避免使列表全局化的危險和定義 class 的開銷,那么我最好的選擇是什么?
import tkinter as tk
def append():
a = a_var.get()
print(a)
print(a[1])
a.append('xyz')
a_var.set(a)
a_arr = ['abc','gh','rstu']
print(a_arr)
window = tk.Tk()
a_var = tk.StringVar()
a_var.set(a_arr)
tk.Button(window, text='Append', command=append).pack()
window.mainloop()
為完整起見,上述代碼返回的 output 和錯誤為
['abc', 'gh', 'rstu']
('abc', 'gh', 'rstu')
'
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\...\Python39\lib\tkinter\__init__.py", line 1884, in __call__
return self.func(*args)
File "c:\Users\...\TestAppend.py", line 7, in modify
a.append('xyz')
AttributeError: 'str' object has no attribute 'append'
如果您的目標是將 append 傳遞給a_arr
,則可以使用lambda
將其傳遞給回調。 回調不需要返回任何內容,因為您將修改 object,而不是用新的 object 替換它。
如果您對代碼進行了以下修改,您會看到每次單擊按鈕時,數組都會增長 1。
def append(a):
a.append('xyz')
print("a:", a)
...
tk.Button(window, text='Append', command=lambda: append(a_arr)).pack()
當然,既然a_arr
已經是全局變量,你也可以直接修改
def append():
a_arr.append('xyz')
...
tk.Button(window, text='Append', command=append).pack()
如果您想使用列表,請將其轉換為StringVar
import tkinter as tk
def append():
print(a_arr)
print(a_arr[1])
a_arr.append('xyz')
a_arr = ['abc','gh','rstu']
window = tk.Tk()
tk.Button(window, text='Append', command=append).pack()
window.mainloop()
按鈕在沒有 arguments 的情況下運行分配的 function - 但您可以使用lambda
更改它並將數組作為參數發送。 但是按鈕也不知道如何處理返回值,因此您無法返回新數組作為return
- 在這里您必須使用全局變量。 當您將所有 GUI 編寫為類時,您可以使用self.
然后還不錯。
import tkinter as tk
class App():
def __init__(self):
self.a_arr = ['abc','gh','rstu']
self.window = tk.Tk()
tk.Button(self.window, text='Append', command=self.append).pack()
self.window.mainloop()
def append(self):
print(self.a_arr)
print(self.a_arr[1])
self.a_arr.append('xyz')
App()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.