如何使用tkinter中的按钮调用单独的python程序



我想在tkinter中创建一个按钮,当按下时,让该按钮将另一个程序调用到该程序中。(这只是一个例子)假设我有一个程序,它显示了一个按钮,上面写着";平方根";我有另一个程序,它使用input()函数获取一个数字,比如:4,并找到4的平方根。我想要按下这个按钮来呼叫";平方根程序";并将其输入到";按钮";程序(再说一遍,只是一个例子。如果我真的想做平方根的事情,我只需要做一个不同的函数,名为:def square_root())

#Button.py
from tkinter import *
root = Tk()
def call_the_other_program():
#This is the part I don't know how to do...
#Do I import the different program somehow?
#Is this even possible xD
b = Button(root, text = "Square root", command = call_the_other_program())

平方根程序:

import math
x = input("input a number")
print("the square root of", x, "is:", math.sqrt(x))
#I want this to be the program that is called

谢谢你给我解释!

您可以在other_prog.py中定义一个函数square_root,导入并调用它。

我建议您先将所有相关文件放在同一个文件夹中,以免使导入过程复杂化。

其他_副本

import math
def square_root():
x = float(input('enter a square'))
return math.sqrt(x)

GUI.py

import tkinter as tk
from other_prog import square_root

def call_square_root():
print(f'the square root is {square_root()}')

root = Tk()
b = Button(root, text = "Square root", command=call_square_root())
b.pack()
root.mainloop()

这个例子有点做作;按钮命令可以直接是square_root,就像导入后的NameSpace中一样。

最新更新