我想要的f2不是它本身,而是f1在執行時完全使用命令結束父函式。我知道這return用于結束一個函式,但它在子級別上不起作用。
所以我的問題是這些命令(或行集)是什么以及如何在我的代碼中實作它們?這里的示例片段:
def f1:
do something
def f2:
do something
# need a command here
f2()
do something
f1()
值得注意的是,代碼while True:在停止函式時要運行一個回圈。我使用 tkinter 庫按鈕來執行子函式(這意味著子函式無法將值回傳給變數),但無法從該組代碼中結束主函式。
這是 tkinter 代碼:
tk.Button(root, text='Click me', command=f2)
這里command = f2在 tk.Button 被按下時執行 f2() ,但沒有在任何地方回傳值。可能可以在 f2 中使用區域或全域變數標志...
從內部函式退出最外部函式的方法? -- 這不能解決我的問題,因為我不能在我的代碼中定義類或錯誤。還有另一種方法嗎?
編輯:我想我無法正確傳達我面臨的問題。
在這一點上它只是一團糟??
import tkinter as tk
from tkinter import messagebox as msgbox
from PIL import ImageTk
lst = []
cnt = 0
black = '#xxx' % (50, 50, 50)
white = '#xxx' % (240, 240, 240)
red = '#xxx' % (255, 80, 80)
yellow = '#xxx' % (255, 220, 80)
green = '#xxx' % (120, 255, 150)
blue = '#xxx' % (0, 220, 240)
purple = '#xxx' % (120, 80, 255)
window_icon = 'icon.jpg'
######## Non-iterables ########
def set_root():
global root
root = tk.Tk() # create only one instance for Tk()
root.withdraw()
def root_attributes():
root.iconphoto(True, ImageTk.PhotoImage(file=window_icon))
root.attributes("-topmost", True)
#################################
def root_win():
global cnt
cnt = 1
set_root()
if cnt == 1:
root_attributes()
global lst
root.deiconify()
w_root = 500
h_root = 320
pos_right = round(root.winfo_screenwidth() / 2 - w_root / 2)
pos_down = round(root.winfo_screenheight() / 2 - h_root / 2)
root.title('Enter the values')
root.resizable(width=False, height=False)
root.geometry('{}x{} {} {}'.format(w_root, h_root, pos_right, pos_down))
root.configure(bg=white)
tk.Label(root, text='Enter the values', font=('bold', 30), bg=white, fg=black).place(x=70, y=20)
tk.Label(root, text='Enter width here:', font=('bold', 15), bg=white, fg=black).place(x=50, y=100)
tk.Label(root, text='Enter height here:', font=('bold', 15), bg=white, fg=black).place(x=50, y=140)
val1 = tk.Entry(root, bd=0, font=('bold', 15))
val1.place(x=280, y=102, width=170)
val2 = tk.Entry(root, bd=0, font=('bold', 15))
val2.place(x=280, y=142, width=170)
lbl = tk.Label(root, text='Min: 5, Max: 100', font=('bold', 15), bg=white, fg=purple)
lbl.place(x=170, y=260)
def enter():
global lst
if val1.get() == '' and val2.get() == '':
lbl.config(text='Please enter width and height!')
lbl.place(x=80, y=260)
elif val1.get() == '':
lbl.config(text='Please enter a width!')
lbl.place(x=145, y=260)
elif val2.get() == '':
lbl.config(text='Please enter a height!')
lbl.place(x=140, y=260)
else:
wid, hit = 0, 0
try:
wid = round(float(val1.get()))
hit = round(float(val2.get()))
except:
lbl.config(text='Please enter value from 5 to 100!')
lbl.place(x=70, y=260)
if not 5 <= wid <= 100 or not 5 <= hit <= 100:
lbl.config(text='Please enter value from 5 to 100!')
lbl.place(x=70, y=260)
else:
lbl.config(text='INPUT ACCEPTED !!!!')
lbl.place(x=130, y=260)
lst = [wid, hit]
root.deiconify()
def clr():
val1.delete(0, 'end')
val2.delete(0, 'end')
lbl.config(text='Min: 5, Max: 100')
lbl.place(x=170, y=260)
enter = tk.Button(root, text='Enter', font=('bold', 15), bd=0, fg=black, bg=green, activebackground=blue,
command=enter)
enter.place(x=300, y=200)
enter.configure(width=8)
clear = tk.Button(root, text='Clear', font=('bold', 15), bd=0, fg=black, bg=red, activebackground=yellow,
command=clr)
clear.place(x=100, y=200)
clear.configure(width=8)
root.mainloop()
# set_root()
root_win()
if not lst:
action = msgbox.askyesno(title='Exit prompt', message='Are you sure you want to exit?\nYes: Exit\nNo: Restart\n',
icon='warning', default='no')
if not action: # Returns True or False
root_win()
else:
quit()
print(lst)
I expect the code to form a GUI for input of 2 values, and if the values do not meet requirements, it should continue GUI interface untill requirements are met. Also, if user closes the GUI in between, there should be a confirm dialogue box to exit or restart "global function". Thing is, root.destroy() help exit global function but some lines are not iterable, like iconphoto. It gives an error.
uj5u.com熱心網友回復:
一種方法是從 引發例外f2,然后捕獲該例外f1,然后提前回傳:
def f1():
# do something
def f2():
print('Hello')
# need a command here
raise StopIteration()
print('World!')
try:
f2()
except StopIteration:
return
print('World')
# do something
f1()
輸出:
Hello
我不確定你在哪里定義while提到的回圈。如果它f1完全在外部,我會在這樣的回圈本身內委托處理錯誤 - 或者你甚至可以while用 try-except包裝回圈,除非絕對需要。如果您采用后一種方法,我建議創建一個自定義例外類,然后捕獲該特定錯誤;通過這種方式,您可以確保您只處理f2例如從內部引發的錯誤。
uj5u.com熱心網友回復:
我有幾種方法可以解決這個問題——這取決于問題的復雜性。
可以像這樣實作簡單的計算:
def foo(*args,**kwargs):
bar = lambda ... : ...
do something
final = bar(x)
return final
foo()
如果函式增加了復雜性,那么使用類(或取決于復雜性的類)是有意義的,如下所示:
class thing_youre_classifying(object):
def __init__(self):
...
def __any_other_boilerplate_methods_needed__(self):
...
def foo(self):
do something
def bar(self):
do something
x = f1()
thing = thing_youre_classifying()
thing.bar()
這主要是為了可讀性(可能還有其他重要的事情)。
或者,如果foo和bar非常不同(比如foo你正在決議一個資料庫并且bar你正在做統計分析),你會想要檢查類繼承。
class foo(object):
def __init__(self, *args, **kwargs)
initialize each instance of foo with args and kwargs
class bar(foo):
def __init__(self):
foo.__init__(self, *args, **kwargs)
instance = bar()
instance.foo()
我想指出的是,我沒有包含*args或**kwargsinbar的樣板 init 函式。這也可能強調的區別foo和bar。
想到的最后一件事是使用裝飾器。
“裝飾器的主要用途之一是它們允許我們向現有函式添加功能,而無需修改原始函式。此功能也擴展到類方法。” ——匿名教授
def foo():
def modifier():
return foo.method_you_want()
return modifier
@foo
def bar():
do something
我的直覺告訴我裝飾器將是最干凈的方式來做到這一點。
uj5u.com熱心網友回復:
沒關系伙計們,我找到了我需要的解決方案:
import tkinter as tk
from tkinter import messagebox as msgbox
from PIL import ImageTk
lst = []
black = '#xxx' % (50, 50, 50)
white = '#xxx' % (240, 240, 240)
red = '#xxx' % (255, 80, 80)
yellow = '#xxx' % (255, 220, 80)
green = '#xxx' % (120, 255, 150)
blue = '#xxx' % (0, 220, 240)
purple = '#xxx' % (120, 80, 255)
window_icon = 'icon.jpg'
def root_win():
global lst
root = tk.Tk() # create only one instance for Tk()
w_root = 500
h_root = 320
pos_right = round(root.winfo_screenwidth() / 2 - w_root / 2)
pos_down = round(root.winfo_screenheight() / 2 - h_root / 2)
root.iconphoto(True, ImageTk.PhotoImage(file=window_icon))
root.attributes("-topmost", True)
root.title('Enter the values')
root.resizable(width=False, height=False)
root.geometry('{}x{} {} {}'.format(w_root, h_root, pos_right, pos_down))
root.configure(bg=white)
tk.Label(root, text='Enter the values', font=('bold', 30), bg=white, fg=black).place(x=70, y=20)
tk.Label(root, text='Enter width here:', font=('bold', 15), bg=white, fg=black).place(x=50, y=100)
tk.Label(root, text='Enter height here:', font=('bold', 15), bg=white, fg=black).place(x=50, y=140)
val1 = tk.Entry(root, bd=0, font=('bold', 15))
val1.place(x=280, y=102, width=170)
val2 = tk.Entry(root, bd=0, font=('bold', 15))
val2.place(x=280, y=142, width=170)
lbl = tk.Label(root, text='Min: 5, Max: 100', font=('bold', 15), bg=white, fg=purple)
lbl.place(x=170, y=260)
def enter():
global lst
if val1.get() == '' and val2.get() == '':
lbl.config(text='Please enter width and height!')
lbl.place(x=80, y=260)
elif val1.get() == '':
lbl.config(text='Please enter a width!')
lbl.place(x=145, y=260)
elif val2.get() == '':
lbl.config(text='Please enter a height!')
lbl.place(x=140, y=260)
else:
wid, hit = 0, 0
try:
wid = round(float(val1.get()))
hit = round(float(val2.get()))
except:
pass
if not 5 <= wid <= 100 or not 5 <= hit <= 100:
lbl.config(text='Please enter value from 5 to 100!')
lbl.place(x=70, y=260)
else:
# lbl.config(text='INPUT ACCEPTED !!!!')
# lbl.place(x=130, y=260)
lst = [wid, hit]
root.destroy()
def clr():
val1.delete(0, 'end')
val2.delete(0, 'end')
lbl.config(text='Min: 5, Max: 100')
lbl.place(x=170, y=260)
def closing():
if msgbox.askyesno(title='Exit prompt', message='Are you sure you want to exit?',
icon='warning', default='no'):
root.destroy()
print('Have a nice day!')
quit()
ext = tk.Button(root, text='Cancel', font=('bold', 15), bd=0, fg=black, bg=red, activebackground=yellow,
command=closing)
ext.place(x=60, y=200)
ext.configure(width=7)
clear = tk.Button(root, text='Clear', font=('bold', 15), bd=0, fg=black, bg=yellow, activebackground=red,
command=clr)
clear.place(x=200, y=200)
clear.configure(width=7)
enter = tk.Button(root, text='Enter', font=('bold', 15), bd=0, fg=black, bg=green, activebackground=blue,
command=enter)
enter.place(x=340, y=200)
enter.configure(width=7)
root.protocol("WM_DELETE_WINDOW", closing)
root.mainloop()
root_win()
print(lst)
關鍵是這個行集:
def closing():
if msgbox.askyesno(title='Exit prompt', message='Are you sure you want to exit?',
icon='warning', default='no'):
root.destroy()
print('Have a nice day!')
quit()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/337154.html
