Configuring a Tkinter Message to display tuples on individual lines - python

I am trying to do what the Title says, Configure the Tkinter message so that each tuple in WL_ratios has its own line without being surrounded in brackets. Creating more messages is not an option as the length of WL_ratios can vary, so i have to only use the one.
#(below) is in the __init__ of the class
self.Leaderboardtext = Message(self.LeaderboardFrame,text="",width=100)
self.Leaderboardtext.pack()
#this (below) is in another function in the same class.
WL_ratios = [["james",3]["harrison",2]["jo",1]]
self.Leaderboardtext.configure(text="Leaderboard: {0}".format(WL_ratios))
So far the width=100 is the only thing that is allowing me to get text onto a new line. However this still isnt working because each tuple varies in length so some tuples spread across two lines which isnt what i want. I know you could limit each line by how number of characters but again the tuples vary in character length so i dont think that is an option.
Does anyone have any suggestions that could work?

Just convert each tuple into a string, and add \n there, and that should do it. Alternatively, you could call each value in the tuple separately, and add \n there.

Related

In python, is there a way to remove all text following the last instance of a delimiter?

I'm trying to create a random text generator in python. I'm using Markovify to produce the required text, a filter to not let it start generating text unless the first word is capitalized and, to prevent it from ending "mid sentence", want the program to search from the back of the output to the front and remove all text after the last (for instance) period. I want it to ignore all other instances of the selected delimiter(s). I have no idea how many instances of the delimiter will occur in the generated text, nor have anyway to know in advance.
While looking into this I found rsplit(), and tried using that, but ran into a problem.
'''tweet = buff.rsplit('.')[-1] '''
The above is what I tried first, and I thought it was working until I noticed that all of the lines printed with that had only a single sentence in them. Never more than that. The problem seems to be that the text is being dumped into an array of strings, and the [-1] bit is calling just one entry from that array.
'''tweet = buff.rsplit('.') - buff.rsplit('.')[-1] '''
Next I tried the above. The thinking, was that it would remove the last entry in the array, and then I could just print what remained. It... didn't go to plan. I get an "unsupported operand type" error, specifically tied to the attempt to subtract. Not sure what I'm missing at this point.
.rsplit has second optional argument - maxsplit i.e. maximum number of split to do. You could use it following way:
txt = 'some.text.with.dots'
all_but_last = txt.rsplit('.', 1)[0]
print(all_but_last)
Output:
some.text.with

How do I find the start and end line number of a selection in QTextEdit cursor?

I have a QTextEdit widget which is showing lines of text. I want the user to be able to select a block of text to be acted on. I need to determine the starting and ending line numbers from the complete text that correspond to the selected block.
editor.textCursor().blockNumber() gives me the correct starting line number but I haven't been able to find the line number of the ending postion.
Finding the length of the selection in lines would be fine.
I'm using PySide and Python 2.7
Use QTextCursor::selectionStart and QTextCursor::selectionEnd to get block start and end position (as an int).
Then get copy of the text cursor, use QTextCursor::setPosition to set position to these two, and use QTextCursor::blockNumber to get the line numbers.
There may be a shorter way, considering how QTextCursor has quite a lot of methods, but this should work. You may want to write a helper method, for example one which takes the position and a QTextDocument or QTextCursor, and returns the line number for that position.

Python variables stored in text files not working, but should be

I've settled on a text-file based save system for my game, storing the values of required variables with keywords - for example, the password that tells the game which chapter to play. However, it appears to be malfunctioning, and I can't see why.
Before starting the game, we have:
if not os.file.isfile('TSGsave{0}.txt'.format(name)):
TSGsave=open('TSGsave{0}.txt'.format(name),'wt')
TSGsave.write('\nw5CT$n<jfW=-#J%4Ya5##')
TSGsave.close()
(the keyword used is a bunch of jibberish so that the user can't change it knowing what's going to happen). This adds w5CT$n<jfW=-#J%4Ya5## to the text file. We then have:
for i in range (len(lines)):
if 'w5CT$n<jfW' in lines[i]:
findpass=lines[i]
for i in range (len(findpass)):
if findpass[i]=='=':
cutfrom=i+1
password=findpass[cutfrom:len(findpass)]
to retrieve the variable (which can change, so it can't be written in as definite value). I know it works, because I added print (password) to the code and it returned -#J%4Ya5##. Then to start the corresponding chapter, the code is:
if password=='-#J%4Ya5##':
but it isn't starting the indented block. In the shell, the program ends and goes back to the >>> line.
If there is a way to fix this code, great - but another code to do the same thing would work just as well.
Your lines contain newlines, and these are being included. Strip these from the line:
findpass = lines[i].rstrip('\n')
Printing a value with a newline in it will simply add an extra black line after the print. Always use the repr() function to produce a Python representation of strings to see such characters:
>>> print '-#J%4Ya5##\n'
-#J%4Ya5##
>>> print repr('-#J%4Ya5##\n')
'-#J%4Ya5##\n'
Your parsing code is overly complicated; you can use str.split() or str.partition() to split your password from the line instead. You should just loop over the lines list directly rather than produce indices with range():
for line in lines:
if 'w5CT$n<jfW' in line:
password = line.partition('=')[2].rstrip('\n')

Tkinter simulating the up/down arrow keys

I need to make my own event handler that includes the standard up/down arrow keys' functionalities in a text widget. However, there are some quirks I have to program around somehow.
You might think you could just add/subtract a line and it would go up/down as expected. Well, that's sort of true. But, if you have the word-wrap on or something, you'll go up further than you expected on wrapped lines. Plus, the arrow key might not go up eveningly as it usually does whether or not the word wrap is on (seeing as it will stay on the same character no matter where that character is).
So, how do I simulate the regular functionality in Tkinter?
Here's why I need to reprogram the up arrow key (down also)—this isn't essential to my question, but because people like to ask and come up with alternative approaches, here you go:
I'm making a text editor, and the natural way it does things in a Tkinter Text widget has a bug that I plan to eliminate. The bug is that if you select text with shift-home or something and then try to select further text with shift-up (or shift-down, or control-shift-left or control-shift-right) then it might select or deselect some inappropriate stuff, depending on how you do it. It should be easy enough to fix control-shift-left and control-shift-right, but I have the positioning problems with shift-up and shift-down. I've already reprogrammed home, end, left, right, shift-left and shift-right for similar reasons (and Tkinter is awesome because you actually can reprogram stuff like this).
I'm using Python 3.4.
I'm thinking maybe getting the x,y coordinates of the insert might be helpful. I didn't see anything for that, though (just the mouse coordinates).
I'm not entirely sure what the problem is that you are having. Are you aware you can ask the text widget to calculate an index of the previous line or next line, and to either take wrapped lines into account or ignore the wrapping?
From the tk text widget docs on index modifiers:
+ count ?submodifier? lines
Adjust the index forward by count lines, retaining the same character position within the line. If there are
fewer than count lines after the line containing the current index,
then set the index to refer to the same character position on the last
line of the text. Then, if the line is not long enough to contain a
character at the indicated character position, adjust the character
position to refer to the last character of the line (the newline).
Spaces on either side of count are optional. If the display
submodifier is given, then each visual display line is counted
separately. Otherwise, if any (or no modifier) is given, then each
logical line (no matter how many times it is visually wrapped) counts
just once. If the relevant lines are not wrapped, then these two
methods of counting are equivalent.
You can also use a minus sign to go backwards.
For example:
next_line = the_widget.index("insert +1 display lines")

python print string on multiple lines

I have a function that can only accept strings. (it creates the image with the string, but the string has little formatting and no word wrapping, so a long string will just bleed right through the edge of the image and keep going into the abyss, when in reality I would have liked it to create a paragraph, instead of a one line infinity).
I need it print with line breaks. Currently the file is being readin using
inputFiles.readlines()
so that this reads the entire file. Storing file.readLines() creates a list. So this list cannot be passed to my function looking for a string.
I used
inputFileContent = ' \n'.join(inputFiles.readLines())
in an attempt to force hard line breaks into the string between each list item. This does not work (edit: elaboration here) which means that the inputFileContent string does not have line breaks even though I put '\n' between the list elements. From my understanding, the readLines() function puts the individual lines into individual elements of a list.
any suggestions? Thank you
Use inputFiles.read() which creates a string. Does that help?
The 'join' should have worked. Your problem may be that the writing of the string ignores newline characters. You could maybe try '\r\n'.join(...)

Categories