我需要從用戶那里獲取一個值,然后把這個值傳給函式,得到一個帶有這個值的字串。我在第一個檔案中的代碼如下(當然,這是簡化版):
import tkinter as tk
from tkinter import ttk
import myfunction # this is my module that has another function[/span]。
class Interface(ttk.Frame)。
def __init__(self, container)。
super().__init__(container)
self.user_price_minimum = tk.StringVar()
minimum_price = ttk.Label(self, text="最低價格是:")
minimum_price.grid(row=0, column=0, padx=5, pady=5)
minimum_price_entry = ttk.entry(self, width=15, textvariable = self.user_price_minimum)
minimum_price_entry.grid(row=0, column=1)
minimum_price_entry.focus()
#############。
button = ttk.Button(self, text="使用價格")
button.grid( column=0, rows=2, columnspan=2, padx=5, pady=5)
root = tk.Tk()
root.geometry("450x250")
root.title("尋找一個單位")
root.columnconfigure(0, weight=1)
frame = Interface(root)
frame.pack()
root.mainloop()
我的另一個呼叫myfunction.py的python檔案應該能夠從用戶那里獲得這個minimum_price,并將其添加到字串中。代碼如下:
def minimum_price(self)。
price_min = self.user_price_minimum.get()
price_min = int(price_min)
print(f'Minimum price is: {price_min}')
因此,我不確定如何將用戶的minimum_price值用在這個函式中。
uj5u.com熱心網友回復:
最簡單的是這樣做:
button = ttk.Button(self, text="Use price", command=lambda: myfunction.minimum_price(self)
但是你也可以在類本身中把它定義為一個方法:
class Interface(ttk.Frame)。
def __init__(self, container)。
super().__init__(container)
self.user_price_minimum = tk.StringVar()
minimum_price = ttk.Label(self, text="最低價格是:")
minimum_price.grid(row=0, column=0, padx=5, pady=5)
minimum_price_entry = ttk.entry(self, width=15, textvariable = self.user_price_minimum)
minimum_price_entry.grid(row=0, column=1)
minimum_price_entry.focus()
#############。
button = ttk.Button(self, text="使用價格", command=print_price)
button.grid( column=0, rows=2, columnspan=2, padx=5, pady=5)
def print_price(self)。
price = self.user_price_minimum.get()
print(f'Minimum price: {price}')
我的個人偏好(當在這樣的情況下使用另一個檔案時(盡管我可能更喜歡如上所述的定義))是如果:
# in the other file.
def minimum_price(value)。
print(f'Minimum price: {value}')
#在類里面
button = ttk.Button(self, text="Use price", command=lambda: myfunction.minimum_price(self.user_price_minimum.get() )
另外,在這種情況下,你不一定需要StringVar,你也可以簡單地通過使用:
# assignment
self.minimum_price_entry = ttk.entry(self, width=15)
# get value (probably in some function call, basically the same way as with the `StringVar` except less code)
self.minimum_price_entry.get()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/310470.html
標籤:
上一篇:安卓11存盤訪問和Java檔案庫
