[英]How to pass string var in callback function using trace() in tkinter
[英]By using tkinter button command, how to pass var from function to local var in main function
我對 python 和 Tkinter 比較陌生,麻煩大家多多包涵。
目前我有 2 個按鈕(一個是打開文件,第二個是運行)和 1 個文本框(Entry 或 Scrolledtext),我想做的是
我面臨的問題是,當我單擊“打開文件”按鈕時,這個局部變量“a”無法更新。 我搜索了這類問題,得到的答案是我應該使用“全局變量”或“制作 class 並將文件路徑視為屬性”。 但不知怎的,我無法做到。 讓我把我的代碼放在下面。
首先是使用全局變量。 我可以通過單擊“btn_run”來獲取更新的 file1,控制台將打印文件 1 的最新值,但 script_path 無法更新。
ps 我也嘗試了 'trace()' 方法。 是的,我發現 var. 在 function 中可以更新,但是如何將這些更新的 var 放入我的局部變量 main 中? 似乎 go 又回到了原點。
from functools import partial
from tkinter import scrolledtext,INSERT,END,Entry, messagebox, filedialog, ttk, Frame,Button
from os import path
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg
# Tkagg allows you to draw, navigation bar is to allow you save, zoomm ....the images
import numpy as np
from tkinter import *
def openfile(txt1):
global file1
file1= filedialog.askopenfilename(filetypes=(("all files","*.*"),("Text files","*.txt"),("csv file","*.csv")))
txt1.insert(0,file1)
# print (file1)
def print_f1():
print(file1)
def main ():
# Create Main window
window = Tk()
file1=''
window.title("WADC FFT trial")
window.minsize(1000,600)
input_str=StringVar()
input_str.set('')
# Create Frame for buttons, bars and picts
mis_frame = Frame(window)
mis_frame.grid(column=0, row=0)
#Create a scrolled text box on mis_frame
txt=Entry(mis_frame,textvariable=input_str,width=40)
txt.grid(column=0,row=0)
#define openfile
#Create a button on mis_frame, use lambda to avoid direct invoke the function called
# btn_path= Button(mis_frame,text="Open File",command=lambda:openfile(txt1))
#another workaround is to use partial funciton in python, assign a new func with lesser variables.
op_func=partial(openfile,txt)
btn_path=Button(mis_frame,text='Open File',command=op_func)
btn_path.grid(column =1,row =0)
script_path=input_str
print('script path is '+str(script_path))
btn_run = Button(mis_frame, text='Run',command=print_f1)
btn_run.grid(column=3,row=0,padx=100)
window.mainloop()
if __name__=='__main__':
main()
第二個帶有 class 屬性。 這個我只做了1個按鈕,可以打開文件並獲取文件路徑。 關鍵是我想將這個'文件名'傳遞給局部變量'a',就像我運行代碼一樣,它將傳遞'a'默認值'文件名'並且在我點擊'瀏覽'后不會更新按鈕。
感謝您提供的建議,這可能會有所幫助
from tkinter import *
import tkinter as tk
class Canvas(tk.Tk): #inherient from Tkinter.tk
def __init__(self):
tk.Tk.__init__(self) #inheritate all attributes that tk has
self.filename ='' #declare filepath
tk.Button(self, text='Browse', command=self.openfile).grid(column=0,row=0)
def openfile(self):
self.filename = filedialog.askopenfilename(title="Open file")
def main ():
b=Canvas()
b.title("Test")
b.minsize(600,400)
a=b.filename
print(a)
b.mainloop()
if __name__=='__main__':
main()
問題
script_path=input_str
將StringVar
分配給 script_path,而不是它的值。 要獲取值,請使用script_path = input_str.get()
當這條線
a = b.filename
執行時,它將 filename 的默認值分配給 a 因為您沒有調用openfile
。
解決方案
要將值傳遞給全局 scope,您既不需要類也不需要全局關鍵字。 只需使用 tkinter 變量
file1 = StringVar()
def openfile(txt1):
file1.set(filedialog.askopenfilename(filetypes=( ("all files","*.*"),("Text files","*.txt"),("csv file","*.csv") ) ) )
txt1.insert(0,file1)
或者讓你的函數返回一些東西。
def openfile(txt1):
file1 = filedialog.askopenfilename(filetypes=( ("all files","*.*"),("Text files","*.txt"),("csv file","*.csv") ))
txt1.insert(0,file1)
return file1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.