I am currently making a monopoly game, and I want to display what my players roll in a label. I have a file dice.py, which has a function roll that rolls the dice (using random.randint(1,6) twice, and adding them). I use a while True just to test it out, but it gives me this error:
TypeError: 'int' object does not support item assignment
when I do
str = ''
strlabel = canvas.create_text(553, 275, text = str, fill='snow3', font=('Times New Roman', 24))
while True:
roll = dice.roll()
str = 'You just rolled a %d!' %(roll)
strlabel["text"] = "hey"
var2 = raw_input()
The raw_input just makes a pause in between each roll. I can't find much on Tkinter out there, so could someone tell me the update text syntax?
The canvas.create_text doesn't create a new label. It create a new item (text) in the canvas and return the id (an int) of the created item.
You have to use the itemconfigure method to configure the item :
canvas.itemconfigure(strlabel, text='You just rolled a %d!'%(roll))
Related
Hello i can only seem to print letters from an entry not the full entry (sentence).
I simply want to click a button using tkinter and after typing a sentence into a box, the button will store the sentences in a list.
Then I want to create a second button that will then print a random sentence from that list.
When I try this it only prints letters of the stored sentence.
Any ideas would be greatly appreciated as I’ve looked around for the last two days before asking.
Best wishes to you all
from tkinter import *
import random
def super_function():
out = map(Entry.get, entr)
clear_entry_1()
def clear_entry_1():
Entry_field.delete(0,END)
def super_function_2():
print(random.choice(entr))
root = Tk()
root.geometry('400x400')
entr = []
for i in range(10):
entr.append(Entry(root))
Entry_field = Entry()
Entry_field.pack()
Button1 = Button(root, text = 'Add your idea!', command =
super_function)
Button1.pack()
Button2 = Button(root, text='Generate an idea!',
command=super_function_2)
Button2.pack()
root.mainloop()
The for loop is useless and should be removed as it just appends 10 invisible entries.
What you need is to append the sentence inside super_function() instead:
def super_function():
# save the sentence
entr.append(Entry_field.get())
clear_entry_1()
I want to plot multiple items in a pyQt4 gui from a list selection which the user can select which plots to show. They can do this as many times as they want. Each time they plot new data, the legend persists even though the plots do not. My code is :
self.DataPlotter.setLabels(left=("magnitude"),bottom=(str(x_ind)))
title = str(y_ind) + " vs " + str(x_ind)
self.DataPlotter.setTitle(title)
self.DataPlotter.addLegend()
for y,c in zip(y_ind,range(len(y_ind))):
self.DataPlotter.plot(self.df[x_ind].tolist(),self.df[y].tolist(), name=y, pen=(c,4))
How do I destroy the old legend each run?
I found the solution here:
https://groups.google.com/forum/#!topic/pyqtgraph/DdWyB1ljQdw
I needed to add this (not sure if try/except is necessary):
try:
self.legend.scene().removeItem(self.legend)
except Exception as e:
print e
Final code looks this:
self.DataPlotter.setLabels(left=("magnitude"),bottom=(str(self.x_ind)))
title = str(self.y_ind) + " vs " + str(self.x_ind)
self.DataPlotter.setTitle(title)
try:
self.legend.scene().removeItem(self.legend)
except Exception as e:
print e
self.legend = self.DataPlotter.addLegend()
for y,c in zip(y_ind,range(len(y_ind))):
self.DataPlotter.plot(self.df[x_ind].tolist(),self.df[y].tolist(), name=y, pen=(c,4))
So im a little new to tkinter and was making a gui. one of the problems i was having was that when i got a value from a entry widget. i could not get the labels that were associated with that entry widget to update after i had done some arithmetic to it. for example
var = tk.StringVar
entry1 = tk.Entry(root, textvariable = var)
entry1.pack()
then do something with var
label1 = tk.Label(root, text = var)
label1.pack()
i looked around before asking this and what i found was to connect the variables. i tried that but it still would not update after the first time.
How would i get the label to update everytime a new value was entered in entry. like if 2 was entered 4 would be displayed. then if i entered 5 then the label should update automatically and 10 should be dislplayed. in this case im just multiplying by two. the label should update until i close the program.
Thanks was having alot of trouble figuring this out any help is appreciated
def enter_hit(event):
do_something_with(var.get())
var = tk.StringVar
entry1 = tk.Entry(root, textvariable = var)
entry1.pack()
label1 = tk.Label(root, text = var)
label1.pack()
entry1.bind("<Return>",enter_hit)
When you hit Enter on entry1, then it calls enter_hit. Then var and it's text can be gotten, and you can do what you want with it to affect label1.
If this doesn't suit you, and you want it to change the moment a character is inputted, then try trace.
def traced_event(event):
do_something_with(var.get())
var = tk.StringVar
entry1 = tk.Entry(root, textvariable = var)
entry1.pack()
label1 = tk.Label(root, text = var)
label1.pack()
var.trace("w", traced_event)
I have a word doc named a.doc formatted:
Name - Bob
Hair color - Red
Age - 28
...
I'd like to save the information after "Name - " "Hair color - " ... into a variable for access later in the script. Would the easiest way be to create a list:
Keywords = (Name, 'Hair color', Age)
Fileopen = open(a.doc)
Filecontent = readlines(fileopen)
For keywords in filecontent:
This is where I get stuck. I'm thinking I can add a statement allowing to grab after the " - " in each line.
EDIT:
To be more precise in my explanation of what I am looking to do:
I would like to grab the information in each line separately after the ' -
' and store it in a variable. For example Name - Bob will be stored in name equaling 'Bob'.
I have made some progress here since my previous update. I just know the way I am doing it does not allow for easily repeating.
I have successfully pulled the information utilizing:
filename = raw_input("choose your file: ")
print "you chose: %r" % filename
with open(filename) as fo:
for line in fo:
if "Name" in line: name = line.split(" - ", 1)[1]
print name
fo.close()
I know that I can continue to make a new 'if' statement for each of my strings I'd like to pull, but obviously that isn't the fastest way.
My REAL question:
How to make that if statement into a loop that will check for multiple strings and assign them to separate variables?
In the end I am really just looking to use these variables and reorder the way they are printed out which is why I need them separated. I attempted to use the 'keywords' but am not sure how to allow that to dynamically define each to a variable that I would like. Should I add them to a list or a tuple and subsequently call upon them in that manner? The variable name obviously has no meaning outside the program so if I called it from a tuple as in [0], that might work as well.
This code asks for the name, age, and hair color of the person, then returns the person's information while storing the information in the variable Filecontent and is stored until you close the shell:
def namesearch(Name, Hair, Age):
Keywords = ('Name - ' + Name + ', Hair Color - ' + Hair \
+ ', Age - ' + Age)
Fileopen = open('a.doc', 'r')
for line in Fileopen:
if Keywords in line:
global Filecontent
Filecontent = line
print line
Name = raw_input('Enter the person\'s name: ')
Hair = raw_input('Enter the person\'s hair color: ')
Age = raw_input('Enter the person\'s age: ')
namesearch(Name, Hair, Age)
This code returns the information in this format:
Name - (Name), Hair Color - (Hair Color), Age - (Age).
Note: This code can only search for names, not add them
def nextItem(self):
active = self.skill_list_listbox.get(tk.ACTIVE)
listbox_contents = self.skill_list_listbox.get(0, tk.END)
current_pos = listbox_contents.index(active)
if current_pos + 1 < len(listbox_contents):
new_pos = current_pos + 1
self.skill_list_listbox.activate(new_pos)
self.skill_list_listbox.selection_set(tk.ACTIVE)
From what I can see within documentation this should highlight and activate the next item in the listbox. If I omit the selection_set I get what I'm looking for but there's no indicator of what's active. Adding it highlights an item, but if you continue to click the "next" button it simply adds to the highlight instead of just highlighting one item creating a long section of highlighted items, which I don't want. I've tried several different methods and this has got me the closest. If there was a 'clear selection' method I suppose I could get my desired effect of just having the next item selected and highlighted, but 3 calls just to do that seems a bit much for a common task? Any thoughts, or suggestions?
Below is an example of what I think you are trying to accomplish, using a button to select the next item in a Listbox. The gist of it is in the button's callback function, which calls selection_clear then selection_set.
Updated the example, hopefully a bit clearer as to what it happening
import Tkinter
class Application(Tkinter.Frame):
def __init__(self, master):
Tkinter.Frame.__init__(self, master)
self.master.minsize(width=256, height=256)
self.master.config()
self.pack()
self.main_frame = Tkinter.Frame()
self.some_list = [
'One',
'Two',
'Three',
'Four'
]
self.some_listbox = Tkinter.Listbox(self.main_frame)
self.some_listbox.pack(fill='both', expand=True)
self.main_frame.pack(fill='both', expand=True)
# insert our items into the list box
for i, item in enumerate(self.some_list):
self.some_listbox.insert(i, item)
# add a button to select the next item
self.some_button = Tkinter.Button(
self.main_frame, text="Next", command=self.next_selection)
self.some_button.pack(side='top')
# not really necessary, just make things look nice and centered
self.main_frame.place(in_=self.master, anchor='c', relx=.5, rely=.5)
def next_selection(self):
selection_indices = self.some_listbox.curselection()
# default next selection is the beginning
next_selection = 0
# make sure at least one item is selected
if len(selection_indices) > 0:
# Get the last selection, remember they are strings for some reason
# so convert to int
last_selection = int(selection_indices[-1])
# clear current selections
self.some_listbox.selection_clear(selection_indices)
# Make sure we're not at the last item
if last_selection < self.some_listbox.size() - 1:
next_selection = last_selection + 1
self.some_listbox.activate(next_selection)
self.some_listbox.selection_set(next_selection)
root = Tkinter.Tk()
app = Application(root)
app.mainloop()