A Concise Guide to Python
3
© David Matuszek, 2011, 2014, 2016, 2017, 2018
Python is open source. It is available from http://www.python.org/download/
and is, at the time of this writing, at version 3.6.2. It comes
with a nice (if very basic) IDE, called idle.
This document describes some of the more commonly useful Python functions and methods. There are very many additional functions and methods, and some of the ones described herein take additional, optional parameters to make them even more useful. See The Python Standard Library documentation for more detailed information.
{...}, or begin...end.
It is then the programmer's responsibility to adjust the indentation
to match. Python dispenses with the braces and uses the indentation
itself to indicate grouping. For example, if 2 + 2 == 4:The first line in a program may not be indented. Lines in the same block must be indented the same amount (4 spaces is standard). Tab characters may be used, but are discouraged, and may not be legal in a future version of Python. Any good editor will have an option to replace tabs with spaces as you type.
print('Arithmetic works!')
print('...as expected.')
else:
print('Somebody goofed up somewhere!')
Each simple statement is written on a separate line. If a line
contains an unclosed '(', '[', or
'{', it is continued on the next line; otherwise, a line
may be continued by ending it with a backslash, '\'.
You can put multiple statements on a line if you separate them
with semicolons, but this is discouraged.
(Major points summarized from PEP 8.)
import statements should be at the top of
the file, and each import should be on a separate
line.camelCaseForIdentifiers.max are okay).(Major points summarized from PEP 257.)
"""...""")._' holds the
value of the previous expression.Functions defined within a class are called methods. Function
calls are written as functionName(arguments),
for example, abs(-5). Method calls are written as object.methodName(arguments),
for example, 'abc'.upper(). All values are objects,
and may have methods.
An integer consists of a sequence of digits. It is decimal (base 10) unless the first digit is zero.
0, 1),
beginning with 0b.0..7), beginning with 0o.0..9, a..f or A..F),
beginning with 0x. A floating point ("real") number includes a decimal
point, an exponent suffix, or both. The exponent consists of an
optional sign, the letter e or E, and
one or more digits.
An imaginary number consists of a decimal integer or a
floating point number, suffixed by j (not
i) or J. A complex number
consists of the sum or difference of an integer or floating-point
number and an imaginary number.
A leading sign, if present, is not counted as part of the number, but as an operator.
abs(x) returns the absolute value of a
number x (or the magnitude of a complex
number).bin(int) returns a binary string
representation of the int.chr(int) returns
the character whose ASCII representation is the int.
The inverse operation is ord. divmod(x, y) returns the
tuple (x // y, x % y)
for integers, (math.floor(x / y),
x % y).float(x) converts
a string or integer x to a floating point
number.hex(int) returns a hexadecimal string
representation of the int.int(x) converts
a string x to an integer, or truncates a
floating point number x to an integer.oct(int) returns an octal string
representation of the int.pow(x, y) returns x
to the power y.round(float) returns the integer
nearest to the given float value.round(float, int) returns the
number float rounded to int
digits after the decimal point.math or random):math.ceil(x) returns the smallest
integer greater than or equal to x.math.floor(x) returns
the largest integer smaller than or equal to x.math.trunc(x)
returns the integer value obtained by dropping everything after
the decimal point.math.func(x), where func
is log, log10, sqrt,
any of the standard trig functions.math.c, where c
is one of the constants pi, e, or tau.random.choice(seq) returns a random
element chosen from the sequence seq.random.shuffle(seq) shuffles the
sequence seq in place.random.random() returns a random floating point
number r in the range 0.0 ≤ r
< 1.0.random.randint(a, b) returns a
random integer r in the range a
≤ r ≤ b.A string is a sequence of zero or more characters,
enclosed in single quotes ('...'), double quotes ("..."),
triple single quotes ('''...'''), or triple double
quotes ("""..."""). It can be treated as a sequence
of characters.
A string may contain "escaped" characters; the most important
ones are \' (single quote), \" (double
quote), \\ (backslash), \t (tab), and
\n (newline).
A raw string is a string prefixed with r or
R. In a raw string the backslash does not escape
characters; all characters stand for themselves.
Triply-quoted strings may extend across several lines, and
include the line breaks as part of the string, unless the line
break is preceded by a backslash ('\'). As in a raw
string, the backslash does not escape characters; all characters
stand for themselves.
A formatted string, or f-string,
is prefixed with f or F. In an
f-string, any expression surrounded by braces, {},
is replaced by its value. To put a brace character in an f-string,
double it. (Note: Python 3.6 or later.)
In Python 3, unlike Python 2, code and strings are in Unicode.
Unicode characters may be entered directly, or by escape
sequences \uXXXX, where the Xs are four
hexadecimal digits, or by \N{name}, where the
name is a standard Unicode name for a
character.
A string occurring by itself (not part of some other statement)
as the first line within a function, method, or class, is a documentation
string, and is stored in the variable named __doc__.
eval(string) evaluates
the string as a Python expression and
returns the result.ord(string) returns
the numeric value of string if it is a
single Unicode character. The inverse operation is chr.
string.center(int) returns a
copy of the string centered in a string
of length int.string.count(substring) returns
the number of non-overlapping occurrences of substring
in the string.string.endswith(suffix) returns
True if the string ends with
the suffix.string.find(substring) returns
the index of the beginning of the first substring
in string, or -1 if not
found.string.format(*args, **kwargs)
returns a formatted copy of string;
see below.string.issomething() tests whether the
string is not empty and every character is of type something,
where:
alnum all characters are alphanumeric |
lower all letters (must be at least one)
are lowercase |
alpha all characters are alphabetic |
printable does not contain control
characters |
digit all characters are digits |
space all characters are whitespace, |
identifier all characters are valid in a
Python identifier |
upper all letters (must be at least one)
are uppercase |
string.ljust(int) returns a
copy of the string left-justified in a field of length int.string.lower() returns a copy of the
string with all letters lowercased.string1.partition(string2)
returns a 3-tuple of (the part of string1
before string2, string2,
and the part after string2).string1.replace(string2, string3)
returns a copy of string1 with all
occurrences of string2 replaced by string3.string.rjust(int) returns a
copy of the string right-justified in a field of length int.string1.split(string2) returns
a list of the substrings of string1 that
are separated by string2. If string2
is omitted, whitespace is used as the separator.string.splitlines() returns a list of
the lines in string, discarding newlines.string.startswith(prefix)
returns True if the string
starts with the prefix.string.strip() returns a copy of string
with all leading and trailing whitespace removed.string.upper() returns a copy of the
string with all letters uppercased.Python has the values True and False,
but in addition, all numeric zero values are false, and all
nonzero values are true. In a numeric expression, True
has the value 1 and False has the
value 0. The special value None
indicates "no value," and is treated as false.
Python has the boolean operators not, and,
and or, with the usual meanings. The and
and or operators are short-circuit; that is, the
second operand is evaluated only if necessary.
A string is an immutable sequence of characters (see above).
A tuple is an immutable sequence of values, not
necessarily all the same type, enclosed in parentheses, ().
To distinguish a one-tuple from a parenthesized expression, put a
comma after the single value, for example, ("just one",).
A list is a mutable sequence of values, not necessarily
all the same type, enclosed in brackets, [].
A range is an iterator that produces a sequence
of integers. range(stop) produces the
integers ; produces the integers ;
and
produces the integers
up to but not including stop. The step
may be negative.
For any sequence or range seq:
seq[i] is the ith
element, counting from zero.seq[i:j] is a copy of
the subsequence of elements seq[i]
up to but not including seq[j].seq[i:] is a copy of the
subsequence of elements starting at seq[i]
and continuing to the end.seq[:j] is a copy of the
subsequence of elements starting at seq[0]
up to but not including seq[j].seq[:] is a copy of the entire
sequence.For any sequence (but not ranges), all the above subsequences are
assignable; that is, they may occur on the lefthand side of the
assignment operator, =.
All ranges and sequence types are iterable. Iterating through a string produces single characters.
reversed(sequence) returns the given sequence
in reverse order. Also works with ranges.The following types are iterable but are not sequences, as the order in which values are stored is determined by their hash codes (dictionary: hash code of the keys), not lexicographically, or by the order in which they are inserted by the programmer.
A set is one or more values, not necessarily
all the same type, enclosed in braces, {}. The empty
set cannot be written as {}; use set()
instead.
set1.isdisjoint(set2) returns True
if set1 and set2
have no elements in common.set1.union(set2) returns the
set of elements in either set1 or set2,
or both.set1.intersection(set2) returns
the set of elements that are in both set1
and set2.set1.difference(set2) returns
the set of elements that are in set1 but
not in set2.set1.symmetric_difference(set2)
returns the set of elements that are in just one of the sets.set1.is_subset (set2) returns True
if every element of set1 is also in set2.set1.is_superset (set2) returns
True if every element of set2
is also in set1.set1 op sets, where op
is one of <, <=, ==,
!=, >=, > can be
used to test subset/superset relations.set.add(element) adds the element
to set.set.remove(element)
removes element from set,
or raises a KeyError if not found.set.discard(element)
removes element from set
if it is present.set.pop() removes and
returns an arbitrary element from set, or
raises a KeyError if the set is empty.set.clear() removes all
elements from set.A dictionary is zero or more key:value
pairs, enclosed in braces, {}. Keys must be
immutable.
globals() returns a live view of the dictionary
of global variables and their values.locals() returns a live view of the dictionary
of local variables and their values.dictionary.get(key) returns the
value associated with the key, or None
if there is no such value.dictionary.get(key,defaultValue)
returns the value associated with the key,
or defaultValue if there is no such
value.dictionary[key] = value
associates the key with the value.del dictionary[key]
removes the key key its value from the dictionary,
or raises a KeyError.dictionary.get[key, default]
returns the value associated with the key,
or (if not found) the default. dictionary.get[key] returns the
value associated with the key, or (if not
found) raises a KeyError. all(iterable) returns True
if no element of the iterable evaluates
to a false value.any(iterable) returns True
if any element of the iterable evaluates
to a true value.filter(test, iterable) applies
the test to each item of iterable
and returns an iterator of the items that pass
the test. To get a list of the items, use list(map(test,
iterable).len(iterable) returns the number of
elements in the iterable.list(iterable) returns a list of the
elements in iterable, in the same order.map(function, iterable) applies
the function to each item of iterable
and returns an iterator of the results. To get
a list of the results, use list(map(function,
iterable).max(iterable) returns the largest value
in iterable.min(iterable) returns the smallest
value in iterable.set(iterable) returns a set of the
values in iterable.sorted(iterable) returns a list of the
elements in iterable, in sorted order.sum(iterable) returns the sum of the
values in iterable.tuple(iterable) returns a tuple of the
elements in iterable, in the same order.zip(iterable,...,iterable) returns
an iterable of tuples of the iterable
values. The length of the iterable is the length of the shortest
iterable.element in iterable returns True
if element is in iterableelement not in iterable
returns True if element
is not in iterableA list comprehension is a way of computing a list from a sequence. There are two general forms:
[expression for variable in sequence]
returns a list of the expression values when each variable
in the sequence is used in the expression.[expression for variable in sequence
if condition] returns a list of the
expression values when each variable in
the sequence that satisfies the condition
is used in the expression.valueIfTrue if condition else valueIfFalsetype(x) returns the type of
object x. Compare it using ==
with any class name, such as int or str,
or the name of a user-defined class.
bool(x) returns False if
the argument x is a false value,
otherwise returns True.str(x) returns a string representing
the object x, as defined by its __str__()
method, if such a method exists. The string should be one
designed to be read by humans.dict(x) returns a
dictionary of name/value pairs, if the argument x is a sequence
of pairs or two-element lists.int(x), float(x),
list(x), set(x), tuple(x)
return the value of x as the named type,
if such a conversion is possible.Comparisons can be chained, for example, 0 < x <=
100.
| Statement type | Examples | Comments |
|---|---|---|
assert expression1 |
assert 2 + 2 == 4
assert x > 0, "Bad value" |
Raises an AssertException if expression1
is false, and has no effect otherwise. The optional expression2
is used as a message by the AssertException. |
variable = expression |
count = 0 |
Assignment. |
var1, ..., varN
= val1, ...,
valN |
name, age = 'Bill', 43 |
Multiple (simultaneous) assignment |
variable op= expression |
count += 1 |
Augmented assignment. v op= ev = v op eop may be any of + - *
/ ** << >> & | ^. |
if expression: |
if x > y: |
Multiple elifs may be used. Using elif
instead of else/if saves a level of
indentation, and makes parallel cases appear parallel rather
than nested. |
for variable in sequence: |
for x in (5, 4, 3, 2, 1): |
The else: clause is done when the loop
exits. |
while expression: |
while x < 1000: |
The optional else: clause is done when the
loop exits. |
break |
break |
Exits the immediately enclosing loop; the else
part, if present, is skipped. |
continue |
continue |
Starts the next iteration of the loop. |
pass |
pass |
Does nothing. Occasionally needed due to the use of formatting rather than punctuation. |
raise exception |
raise ValueError |
Raises an exception. The value is any
expression, used as a message in the exception. By itself in
an except clause, raise by
itself re-raises the same exception. |
try: |
try: |
The expression and variable
are optional. The optional else clause, if
present, is executed if no exception was raised. |
try: |
try: |
The expression and as variable
are optional. The optional finally clause, if
present, is executed whether or not an exception was raised. |
del variable |
del x |
Deletes a variable. |
exec expression |
exec "print('hello')" |
Executes a string, open file object, or code object. |
import module |
from java import util |
Names may be changed when imported. When using the *, imported methods don't need
to be prefixed with the name of the source file. |
global var1, ..., varN |
global max, min |
Any variable given a value within a function is local to that function unless declared global in the function. |
return |
return result |
As in Java. |
yield value |
yield n |
Returns the next result when next(iterator)
is called. |
class name: |
class student (person): |
Declares a class and tells what classes it extends. |
def name (parameters): |
def sum (x, y): |
Declares a function. The Documentation string
tells the purpose of the function. |
The simplest form of a named function is:
def functionName(parameter1, ..., parameterN):
"""Optional but strongly recommended documentation string goes here."""
# Statements, possibly including a return statement
In Python functions are values, and can be assigned to variables.
For example, absval = abs makes absval
a synonym for abs, and absval(-5) will
return 5. As values, they may be passed as arguments
to other functions, and returned as the result of other functions.
The form of an anonymous function is:
lambdaparameter1, ..., parameterN: expression
Parameters must be simple names, not expressions. The function
can be called by giving its name and values for the parameters,
for example, average(3.5, y). Parentheses are
required, in both the function definition and the function call,
even if the function does not take parameters.
Note: Parameters in the function definition are sometimes called "formal parameters"; values in the call to a function are called "actual parameters" or "arguments". Sometimes formal parameters are also called "arguments", though this is an incorrect usage.
Every function returns a value. Use statements of the form return
value to specify the value to return. Omit the value,
or simply "flow off" the end of the function, to return the
special value None.
With no additional syntax, arguments are matched to parameters by position.
Parameters in a function definition may be:
variable=value, to give a
default value for missing arguments*variable, to accept multiple arguments
as a single tuple**variable,
to accept multiple keyword arguments as a single tuplename=value, to give a value to
the parameter with that name (or "keyword")*tuple, to pass a tuple as separate
arguments**dictionary, to
pass in values to multiple parameters by nameThe scope of a name is the part of the program in which the name has meaning and can be used.
To simplify somewhat, Python has two scopes: local and global. Local variables are those defined within a function or method, and are available only within that function or method. Global variables are those available throughout the program. Local and global variables are in different namespaces, so the same name can be used both locally and globally, with different values (though this is confusing and should be avoided).
Terminology: To "read" a variable is to get the value it contains; to "write to" a variable is to change that value.
Python's rules are goofy
somewhat unusual.
global
variableName.input() or input(prompt)
reads one line, as a string, from the user.
split
method to separate them.strip
leading and trailing spaces from the input.eval to convert
the input string to a Python value (int, float, etc.) print(expr1, ..., exprN, sep=sepString,
end=endString, file=outputFile)
evaluates and prints the expressions, with
sepString between them, and endString
after the last expression, on outputFile.
The keyword arguments sep, end, and file
may be omitted, with the default values
(a single space), '\n' (a newline), and stdout,
respectively.
print() can be used to print a blank line.format
string method may be used.To do file I/O you must (1) open the file, (2) use
the file, and (3) close the file.
file = open(fileName, mode)
opens and returns (in file) a reference
to the named file; mode is
'r' to read the file (this is the default if
mode is omitted) 'w' to erase and write the file'a' to append to the end of an existing file'r+' to both read and write.'rb', 'wb', 'ab',
'rb+' to do binary input/outputmode, add encoding='utf-8'
for Unicode filesfile.read() will read in and return the
entire file.file.readline() reads and returns a line
of text, including the terminating newline (if any). If the
empty string is returned, the end of the file has been reached.file.readlines() reads the entire file
and returns it as a list of strings, including terminating
newlines. for line in
file: loopBody file.write(string) writes the string
to the file, and returns the number of
characters written. file.close() closes the file. Mandatory.
Leaving the file open when you are done with it will
cause problems.with open(fileName) as file: loopBody
will automatically close the file when done, even if
exceptions occur. Text (default, non-binary) mode converts platform-specific line endings to the current platform. This will corrupt binary files. Text files, on the other hand, can be read and written as binary without harm.
First, import os. Then,
os.getcwd() to get the current working directory.os.chdir(path) to change the current
working directory to path. os.listdir(path='.') to return a list
containing the names of the entries in the directory given by path.os.mkdir(path, mode=0o777, *,
dir_fd=None) to create a directory named path
with numeric mode mode. os.remove(path, *, dir_fd=None) to
delete the single file path; not for
directories.os.rmdir(path, *, dir_fd=None) to
remove (delete) the empty directory path. os.rename(src, dst) to rename
the file or directory src to dst. os.walk(top, topdown=True, onerror=None,
followlinks=False) to generate the file names in a
directory tree by walking the tree either top-down or bottom-up.
For each directory in the tree rooted at directory top
(including top itself), it yields a
3-tuple (dirpath, dirnames,
filenames).A unit test is a test of the methods in a single class. A test case tests the response of a single method to a particular set of inputs. To do unit testing,
import unittestimport fileToBeTested or from
fileToBeTested import *
class NameOfTestClass(unittest.TestCase):
def setUp(self) and def
tearDown(self) if wanted. def testSomething(self)
methods (names must begin with test).setUp is called before each test case, and should
initialize everything to a "clean" state.
tearDown is called after each test case, to remove
artifacts (such as files) that may have been created.
If you use from file import * then you
don't have to precede every function call with the name of the
file it was imported from.
The following are some of the methods available in test methods:
assertEqual(a, b), assertEqual(a,
b, message)assertNotEqual(a, b), assertNotEqual(a,
b, message)assertAlmostEqual(a,
b), assertAlmostEquals(a, b, places),
assertAlmostEquals(a, b, places,
message)assertTrue(x), assertTrue(x, message)
assertFalse(x), assertFalse(x, message)
assertIs(a, b), assertIs(a,
b, message) assertIsNot(a, b), assertIsNot(a,
b, message) assertIsNone(x), assertIsNone(x, message)
assertIsNotNone(x), assertIsNotNone(x,
message) assertIn(a, b), assertIn(a,
b, message) assertNotIn(a, b), assertNotIn(a,
b, message) assertIsInstance(a, b),
assertIsInstance(a, b, message) assertNotInstance(a, b),
assertNotInstance(a, b, message)
assertRaises(exception, function name,
arguments to function)Typically b and x
are calls to the method being tested, while a
is the expected result. The message is
optional, and only used if there is some reason to provide
additional information.
Arguments to a function are always evaluated before the function
is called. Therefore, the assertRaises test must
have the above special form, so that the call to the tested
function can be delayed, then called from within the assertRaises
method.
A common idiom is to put a call to the main function as the last
line in the code file, for example, main(). This
causes the main method to run immediately after the file is
loaded. When doing unit testing, this is undesirable. Instead,
replace that line with
if __name__ == '__main__':
main() # or however you want the program to start
and put the following code at the end of the test file:
unittest.main()In this way, the program will be run if loaded from the program file, and the tests will be run if loaded from the test file.
Unit tests can be combined into a test suite.
If file testfoo.py contains the class TestFoo,
and file testbar.py contains the class TestBar,
the test suite can be written like this:
import unittest import testfoo, testbar def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(testfoo.TestFoo)) suite.addTest(unittest.makeSuite(testbar.TestBar)) return suite if __name__ == '__main__': test_suite = suite() runner = unittest.TextTestRunner() runner.run (test_suite)
A class describes a new type of object, and bundles together the methods used for working with objects of that type. The syntax for defining a class is
class ClassName(NameOfParentClass):variable and method definitions
where NameOfParentClass
is the name of the superclass (usually object).
To create an instance (object) of a class, use the name of the class as if it were a function name.
The class being defined inherits all the variables and methods of the parent class.
To allow parameterized creation of new objects, define a method
named __init__ within the class. The first
(required) parameter of this method is conventionally named self
and refers to the object being created. To create an instance, do
not call __init__; use the name of the
class as if it were a function name, and supply values for all the
parameters except self. To create instance
variables in __init__ (or any other method), use self.name=value.
To call a method defined in an object (more properly called
"sending a message to the object"), use the syntax object.method(arguments).
To call a method from another method defined within the same
object, use the syntax self.method(arguments).
To access a variable defined in an object from within the same
object, use the syntax self.variable. To
directly access a variable defined in a different object, it is
legal to say object.variable, but
this is frowned upon.
If you define a method __str__(self), this method
will be called when the object is printed; therefore, it should
return a humanly-readable string. It can also be called directly
by str(object).
repr(x) returns a string representing the
object x, as defined by its __repr__()
method, if such a method exists. Where possible, the string is one
that can be read by Python to reconstruct the object.
For comparing objects, you may define the methods __lt__(self,
other), __le__(self, other),
__eq__(self, other), __ne__(self, other),
__ge__(self, other), __gt__(self, other),
and these are used by the corresponding Python operators. There
are no implied relationships among these methods.
There are several GUI systems that can be used with Python. This section discusses Tkinter, which comes bundled with the standard Python distribution. Another system of interest is WxPython, because there are versions of Wx for various other programming languages (even Java).
GUI programs work differently than programs without a GUI.
Instead of all code under control of a main method,
the program creates a GUI, and thereafter everything that happens
is a result of some interaction with the GUI. For example, the
user clicks a button, and that causes certain code to be executed.
Start with
from tkinter import *
import tkinter.ttk
After that, your code should create a window,
top = Tkinter.Tk()
# Populate the window with widgets (see below)
And turn over execution to it:
top.mainloop()
There are three main tasks to be performed: (1) Create some widgets (buttons, text areas, etc.) , (2) Arrange the widgets in the window, and (3) Associate code with some of the widgets.
There are 15 types of widgets in Tkinter, each with many options,
indicated with option=value. This
will cover only the most common types and options. For much more
detail, TutorialsPoint
is an excellent reference. (In the following, we assume that the
window is called top.)
fr = Frame(parent, option, ...)parent may be the top-level window (top) or another Frame. Some useful options are bg=color, the background color (as a color name or hex number) and bd=n, the border width in pixels.but = Button(top, text=string, command=function)string,
which when clicked will call the function.lab = Label(top, text=string)ent = Entry(top, width=n)n
characters, into which the user can type a single line of text.
Any number of characters may be entered.ent.get().txt = Text(top, width=num_characters, height=num_lines)num_characters wide
and num_lines high, into which the user
can type multiple lines of text. Any number of lines may be
entered.txt.get(1.0, END)var = IntVar()
chk = Checkbutton(top, text=string, variable=var,
command=function)var.get() will return 1 if
checked, 0 if not checked.There are three methods for arranging widgets into the main window and into Frames. Only one of these methods should be used in any given window or Frame.
widget.pack(options)side=side where side is one of LEFT, RIGHT, TOP, or BOTTOM to add widgets starting from that side.expand=True to expand the widget to fill available space.fill=how to expand the widget, where how is X (horizontally), Y (vertically), BOTH, or NONE.widget.grid(options)row=n The row to put the widget in. Default is first available row.column=n The column to put the widget in; default is 0.rowspan=n, columspan=n The number of rows/columns the widget should occupy.ipadx=n, ipady=n The amount (in pixels) to pad the widget, horizontally and vertically.sticky=d Where to put the widget if in a larger space. d is one of N, S, E, W, NE, SE, NW, SW.widget.place(options)x=px, y=px The x and y position of the anchor point of the widget, relative to the parent.anchor=d Which part of the widget the x and y refer to. d is one of N, S, E, W, NE, SE, NW, SW, default is NW.bordermode=OUTSIDE to take the parent's border into account when positioning the widget, else INSIDE (default).height=px, width=px The height and width of the widget, in pixels.relx=float, rely=float The x and y position, as a fraction between 0.0 and 1.0, of the width and height of the parent.relwidth=float, relheight=float The size of the widget, as a fraction between 0.0 and 1.0, of the width and height of the parent.