简体   繁体   English

有没有办法在 Python 中使用 f-string 的函数中使用变量?

[英]Is there a way to use a variable in a function with f-string in Python?

I have 2 variables n1 and n2 .我有 2 个变量n1n2 When I press space randNum is either equal to 1 or 2 and if it is equal to 1 then I want to change n1 and if it is equal to 2 then I want to change n2 .当我按下空格时randNum要么等于 1 要么等于 2,如果它等于 1 那么我想改变n1 ,如果它等于 2 那么我想改变n2 I am using .itemconfig() to change the variable but I do not know how to asign it to the variable that I want to change.我正在使用.itemconfig()来更改变量,但我不知道如何将其分配给我想要更改的变量。 I tried to somehow do it with f-string but that does not work.我试图以某种方式用 f-string 做到这一点,但这不起作用。 Is there any way to do it?有什么办法吗? Here is my code:这是我的代码:

import tkinter as tk
import random


canvas = tk.Canvas()
canvas.pack()


n1 = canvas.create_text(100, 100, font="Arial 25", text="1")
n2 = canvas.create_text(100, 150, font="Arial 25", text="2")


def function(event):
    if event.keysym == 'space':
        randNum = random.randint(1,2)
        canvas.itemconfig(f"n{randNum}", font="Arial 25", fill="red", text=randNum) #does not work


canvas.bind_all('<Key>', function)


tk.mainloop()

You can use tags option of create_text() :您可以使用create_text() tags选项:

n1 = canvas.create_text(100, 100, font="Arial 25", text="1", tags="n1")
n2 = canvas.create_text(100, 150, font="Arial 25", text="2", tags="n2")


def function(event):
    if event.keysym == 'space':
        randNum = random.randint(1,2)
        canvas.itemconfig(f"n{randNum}", font="Arial 25", fill="red", text=randNum)

If you wish the text colors to oscillate between black and red then here is one option.如果您希望文本颜色在黑色和红色之间振荡,那么这里是一种选择。

n0 = canvas.create_text(100, 100, font="Arial 25", text="1")
n1 = canvas.create_text(100, 150, font="Arial 25", text="2")

def function(event):
    r  = random.randrange(2)
    c = [ "red", "black" ]
    if r: c.reverse()
    canvas.itemconfig( f"{n0}", fill=c[0] )
    canvas.itemconfig( f"{n1}", fill=c[1] )


canvas.bind_all( '<space>', function )

You need to use tags你需要使用标签

import tkinter as tk
import random

def function(event=None):
    rand_num = random.randint(1,2)

    # resetting the color of existing elements
    for i in range(1, 3):
        canvas.itemconfig(f"tag{i}", font="Arial 25", fill="black")

    # highlighting the active one
    canvas.itemconfig(f"tag{rand_num}", font="Arial 25", fill="red")


canvas = tk.Canvas()
canvas.pack()

n1 = canvas.create_text(100, 100, font="Arial 25", text="1", tags="tag1")
n2 = canvas.create_text(100, 150, font="Arial 25", text="2", tags="tag2")

canvas.bind_all('<space>', function)

tk.mainloop()

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

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