python 如何从模块中启动函数,使其在主程序中生效?

wfsdck30  于 2023-05-27  发布在  Python
关注(0)|答案(2)|浏览(92)

我想得到的一个例子:
主程序:

from tkinter import *
import tkinter  as tk 
import module

main_window = Tk()

def createCanvas():

    canvas = Canvas(main_window, bg="grey")
    canvas.grid(row=1, column=0, columnspan=2)

def resetCanvas():

    canvas.destroy()
    createCanvas()

button1 = Button(main_window, text="launch module", command=module.moduleFunction)
button1.grid(row=0, column=0)

button2 = Button(main_window, text="reset canvas", command=resetCanvas)
button2.grid(row=0, column=1)

createCanvas()

main_window.mainloop()

模块:

from tkinter import *
import tkinter  as tk
from tkinter import Toplevel

def moduleFunction():

    child_window = Toplevel()

    def resetCanvasFromModule():

        # THE QUESTION!
        resetCanvas() 

    button3 = Button(child_window, text="reset canvas from module", command=resetCanvasFromModule)
    button3.grid(row=0, column=0)

显然这不起作用,因为resetCanvas()没有在模块中定义,但是如果我定义了它,它会试图销毁canvas,而canvas没有在模块中定义,所以它也不会起作用。
我该怎么做才能得到我想要的效果呢?
PS:我试过“全球”,没有成功。

ql3eal8s

ql3eal8s1#

谢谢你们的帮助。
将resetCanvas()作为参数传递给moduleFunction(),并将lambda作为button1命令,可以正常工作。
这是我的工作示例代码(也许将来它对像我这样的新手有用):
主代码:

from tkinter import *
import tkinter  as tk 
import module

main_window = Tk()

def createCanvas():
    global canvas
    canvas = Canvas(main_window, bg="grey")
    canvas.grid(row=1, column=0, columnspan=2)
    return
    canvas

def resetCanvas():

    canvas.destroy()
    createCanvas()

button1 = Button(main_window, text="launch module", command=lambda:[module.moduleFunction(resetCanvas)])
button1.grid(row=0, column=0)

button2 = Button(main_window, text="reset canvas", command=resetCanvas)
button2.grid(row=0, column=1)

createCanvas()

main_window.mainloop()

模块:

from tkinter import *
import tkinter  as tk
from tkinter import Toplevel


def moduleFunction(resetCanvas):

    child_window = Toplevel()

    def resetCanvasFromModule():
        
        resetCanvas() 

    button3 = Button(child_window, text="reset canvas from module", command=resetCanvasFromModule)
    button3.grid(row=0, column=0)

多谢了。

eufgjt7s

eufgjt7s2#

你不能直接传递元素吗?类似于tkinter import *

canvas = None

def createCanvas():
    global canvas
    canvas = Canvas(main_window, bg="grey")
    canvas.grid(row=1, column=0, columnspan=2)

def ResetCanvasFromModule():
    global canvas
    canvas.forget()
    createCanvas()

button1 = Button(main_window, text="create canvas", command=createCanvas)
button1.grid(row=0, column=0)

button2 = Button(main_window, text="reset canvas", command=ResetCanvas)
button2.grid(row=0, column=1)

相关问题