简体   繁体   English

如何“激活”代码的某些部分

[英]How to “activate” certain parts of a code

I want to "activate" parts of my code through buttons. 我想通过按钮“激活”我的代码部分。 I tried something like, when you press a button, the value of a variable is set to an other amount which activates another part of my code: 我尝试过类似的操作,当您按下按钮时,变量的值将设置为另一个值,从而激活代码的另一部分:

from tkinter import *
window = Tk()
window.title('Adventure')
c = Canvas(window, height=360, width=640, bg='black')
c.pack()

system = 1

def start():
    c.delete(anfang1)
    anfangbutton.destroy()

if system == 1:
    anfang1 = c.create_text(320, 180, text='Adventure', fill='white', font=('Halvatica', 50))
    anfangbutton = Button(window, text='Start', command=start)
    anfangbutton.place(x=320, y=250) # I want that if you press the button, start is activated and the value of "system" goes to 2, so the next part begins
if system == 2:
    anfang2 = c.create_text(320, 180, text='Adventure', fill='white', font=('Halvatica', 50))

I would appreciate if someone could help me with this or has another way of doing it 如果有人可以帮助我或者有其他方法可以帮助我,我将不胜感激

Here is the code, I will explain: 这是代码,我将解释:

def nextStage():
     #CODE#

def start():
    c.delete(anfang1)
    anfangbutton.destroy()
    anfang2 = c.create_text(320, 180, text='Adventure', fill='white', font=('Halvatica', 50))
    #then button or code to move onto next "stage"

def main():
    global anfang1
    global anfangbutton
    anfang1 = c.create_text(320, 180, text='Adventure', fill='white', font=('Halvatica', 50))
    anfangbutton = Button(window, text='Start', command=start)
    anfangbutton.place(x=320, y=250) # I want that if you press the button, start is activated and the value of "system" goes to 2, so the next part begins
main()

Basically, what I have done to try and combat the issue is two things. 基本上,我为解决这个问题所做的是两件事。

Rather than trying to use a system variable and If/Else statements, I have put it all into functions. 我没有尝试使用系统变量和If / Else语句,而是将其全部放入函数中。 For tkinter, you want to build functions from the first one at the bottom of the page. 对于tkinter,您想从页面底部的第一个构建函数。 So the last "stage" or function will be at the top (this is just so it can be properly referenced by the button). 因此,最后一个“阶段”或功能将在顶部(这是为了可以通过按钮正确地引用它)。

I then globalised the variables so that start() would be able to destroy the buttons. 然后,我对变量进行了全局化,以便start()能够销毁按钮。

Not the most effective but works? 不是最有效但是有效吗?

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

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