I am attempting to make a rogue clone in python using Tkinter, I found using .update would work better for what I want to do but unfortunately when I print out the string, it prints it out, and out and out
while True:
print(key_press)
if key_press == "d":
current_player_col = 1
map_layout[current_player_col][current_player_row] = "P"
map_layout_printable = ""
for row in range(len(map_layout)):
for column in range(len(map_layout[row])):
map_layout_printable = map_layout[row][column]
map_layout_printable = "\n"
message = tk.Label(root, text=map_layout_printable)
message.pack()
root.update()
Is there a way of being able to update the string without printing it out over and over again?
CodePudding user response:
You have your print statement inside your while loop without a break condition. If you are looking for something that runs until a condition is met you need something like this to stop it from printing once the condition is met. Your statement perpetually evaluates to True so it will just keep printing whatever key_press value is. The print statement needs to be after the condition.
data = [1, 2, 3, 4]
while True:
item = int(input("Enter a number:"))
if item in data:
print("Found!")
break
else:
print("Not Found")
CodePudding user response:
There are mulitple things that could be fixed with your code.
window = tk.Label(root, text="")
window.pack()
width = 8
height = 8
mp = [["0" for i in range(width)] for i in range(height)]
keypress = None #For now
def convertMapToText(mp1: list) -> str:
strs = []
for row in mp1:
strs.append("".join(row) "\n")
return "".join(strs)
while True:
print(keypress)
#key input handler here
window["text"] = convertMapToText(mp)
root.update()
#1 : Use <labelObject>["text"]
. This will let you modify the text in the widget in a much more clean and performance-friendly way.
#2 : Based on your code snippet, you shouldn't do for row in range(len(<list>))
, this has significantly more function calls as well as more memory consumption. Do for row in <list>
. This sets row
to the row the loop is currently iterating through. For example...
lst = [[0 for i in range(4)] for e in range(4)]
for row in lst:
print(row)
This code bit would print this...
[0,0,0,0]
[0,0,0,0]
[0,0,0,0]
[0,0,0,0]
#3 : I added a convertMapToText
function which cleaned up and organized your code. This isn't entirely necessary but it made it much more readable.
#4 : To prevent confusion, when you put a for
loop in a list, it allows you to more efficiently fill a list or matrix (a list of lists in this case) without needing to call extra functions or increase your memory footprint.
#5 : Also, at line 6, you will get thrown a IndentationError
because it doesn't match the indentation of the lines around it.
As for the main part of your question, I assume you mean the variable keypress
keeps printing. This is because it is in a while
loop. If this is not the case, then I am unsure. Your code lacks any other print
statements.