[英]How do I call a separate python program using a button in tkinter?
我想在 tkinter 中创建一个按钮,按下时,让该按钮将不同的程序调用到该程序中。 (这只是一个例子)假设我有一个程序显示“平方根”按钮,而我有另一个程序接受一个数字,例如:4,使用 input() function,并找到平方根4.我希望那个按钮在按下时调用“平方根程序”并将其输入到“按钮”程序中。 (再次。只是一个例子。如果我真的想做平方根的东西,我会做一个不同的 function 称为: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)
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
中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.