繁体   English   中英

如何使用Tkinter制作计时器?

[英]How to make a timer with tkinter?

我正在尝试制作一个计时器,以关闭运行Linux的计算机。 要选择我使用Spinbox的时间。 因此,想法是在微调框中选择时间量,然后将其添加到命令sudo shutdown -P + 15分钟(例如示例)。

到现在为止,它只是关闭了,我做不到一个简单的方法。

计时器程序

from tkinter import *
import os
import time

def shutdown():
    hrs = spin1.get()
    command1 = ('sudo shutdown -P')
    #sum1 = command1 + hrs
    os.system('sudo shutdown -P') + ('hrs')
    print(os.system)

def cancel():
    command = ('sudo shutdown -c')
    os.system('sudo shutdown -c')
    print(command)



'''def hrs():
    spn1 = spin1.get()
    dsp1 = spn1
    lbltime ['text'] = dsp1'''

entry_width = 2
win = Tk()

spin1 = IntVar()
spn = IntVar()

win.title('SHUTDOWN')
win.geometry('300x250+300+150')
lbl = Label(win, text='SET YOUR SHUTDOWN')
lbl.place(x=80, y=30)


spin1 = Spinbox(win, from_=00, to=23, font=('arial',26,'bold'), width= entry_width, textvariable=spin1)
spin1.insert(0, '00')
spin1.place(x=130, y=60)

setup = Button(win, text='SET TIMER', font=('arial',16,'bold'), command=lambda :shutdown())
setup.place(x=90, y=130)

cnc = Button(win, text='CANCEL', font=('verdana',10, 'bold'),command= lambda :cancel())
cnc.place(x=120, y=180)

win.mainloop()

为了将您的hrs (用户选择的分钟数)添加到命令中,您可以使用+或使用format()将其添加到现有的字符串命令中,如我在解决方案中所示。 同样,当使用sudo运行命令时,您需要输入密码,要自动执行此操作,您可以使用-S参数,这使sudo从STDIN读取密码,此处为"mypassword"

def shutdown():
    hrs = spin1.get()
    sd_command = 'echo mypassword | sudo -S shutdown -P +' + hrs # both will work
    sd_command = 'echo mypassword | sudo -S shutdown -P +{}'.format(hrs)
    os.system(command)
    print(command)

def cancel():
    cancel_command = 'echo mypassword | sudo -S shutdown -c'
    os.system(cancel_command)
    print(cancel_command)

如果要添加有关关闭计划的消息,则需要添加另一个标签, shutdown_schedule将显示var_schedule内容,该内容是var_schedule字符串变量,将在用户安排或取消关闭时进行修改。

def shutdown():
    hrs = spin1.get()

    sd_time = time.strftime("%H:%M", time.localtime(time.time() + 60*int(hrs)))
    var_schedule.set('Shutdown scheduled for {}'.format(sd_time))

    sd_command = 'echo mypassword | sudo -S shutdown -P +' + hrs # both will work
    sd_command = 'echo mypassword | sudo -S shutdown -P +{}'.format(hrs)
    os.system(command)
    print(command)

def cancel():
    var_schedule.set('Shutdown not scheduled yet')

    cancel_command = 'echo mypassword | sudo -S shutdown -c'
       os.system(cancel_command)
    print(cancel_command)

var_schedule = StringVar()
var_schedule.set('Shutdown not scheduled yet')

shutdown_schedule = Label(win, textvariable=var_schedule)
shutdown_schedule.place(x=130, y=30)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM