【问题标题】:Python run script when Tkinter button pressed按下 Tkinter 按钮时 Python 运行脚本
【发布时间】:2017-08-10 13:02:41
【问题描述】:

我试图让它在使用按钮(命令提交)时设置变量fpl。问题是,它在用户点击按钮之前贯穿了整个事情。我怎样才能让脚本开始?

#Convert string to list
fpl = fpl.replace(" " , ".")

只有在用户按下按钮后才运行?下面的其余代码。

import json
from tkinter import *

def submit():
    fpl = entry.get()

window = Tk()
window.title ("Infinite FMS")

Label (window, text="Enter your flight plan 
here:").grid(row=0,column=0,sticky=W)

entry = Entry(window, width = 75, bg = "light blue")
entry.grid(row=1,column=0,sticky=W)

Button (window, text="Submit", 
command=submit).grid(row=2,column=0,sticky=W)

output = Text(window,width=75,height=6,background="light 
blue")
output.grid(row=3,column=0,sticky=W)

#Convert string to list
fpl = fpl.replace(" " , ".")

"[" + fpl + "]"

fpllist = fpl.split(".")
#Length of fpllist
fpllen = len(fpllist)

#Loop through the flight plan missing first and last 
entries
n = 1
Invalid = []
while n < fpllen - 1:
    #Check for item in file
    searchTerm = (fpllist[n])
    searchTermF = "\'Name\': \'" + searchTerm + "\'"
    searchTermV = "\'identifier\': \'" + searchTerm + "\'"
    file = open('mydirectory', 'r')
    data1 = json.load(file)
    file.close()
    file = open('mydirectory', 'r')
    data2 = json.load(file)
    file.close()
    if searchTermF in str(data1):
        Validity = "Your route is valid!"
        n = n + 1
    elif searchTermV in str(data2):
        Validity = "Your route is valid!"
        n = n + 1
    else:
         Validity = "Your route is invalid!\nInvalid 
waypoints:"
    Invalid.append(searchTerm)
    n = n + 1                    
if len(Invalid) == 0:
    print (Validity , ', '.join(Invalid))
else:
    Validity = "Your route is invalid!\nInvalid 
waypoints:"
    print (Validity , ', '.join(Invalid))

output.delete(0.0, END)
output.insert(END, (Validity , ', '.join(Invalid)))

【问题讨论】:

  • 我没有仔细检查过你的代码,但是你为什么不把fpl = fpl.replace(" " , ".") 以后的所有东西都放在submit 函数中呢?
  • 请您查看并相应修改stackoverflow.com/help/mcve
  • 目前尚不清楚您究竟想将fpl 格式化为什么,以及格式化后您想对fpl 做什么。此信息将有很大帮助。请在代码中修正缩进。

标签: python python-3.x user-interface tkinter


【解决方案1】:

正如 PM 2Ring 所说,如果你放这个

#Convert string to list
fpl = fpl.replace(" " , ".")

"[" + fpl + "]" #what is this supposed to do?

fpllist = fpl.split(".")
#Length of fpllist
fpllen = len(fpllist)

在您的submit 函数中,当您单击按钮时它将运行。 此外,您不需要用点替换空格 fpllist = fpl.split() 会得到相同的结果。

你真的应该学习 OOP(如果你不知道它是什么,请谷歌它)它将使你的程序更具可读性,并且你可以将程序的不同部分拆分为不同的函数。

【讨论】:

    猜你喜欢
    • 2018-01-28
    • 2021-06-09
    • 2021-12-20
    • 2023-01-23
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 2021-10-16
    • 2022-12-25
    相关资源
    最近更新 更多